Tests are the code most developers skip — and the code they most regret skipping. AI removes the main barrier (tedium) and adds a bonus (it catches edge cases humans forget). Here's how to use AI for test writing effectively.
The AI Test Generation Prompt
"Write unit tests for this function/class: [PASTE CODE]. Requirements: Use [Jest/PyTest/JUnit/etc]. Cover: happy path, edge cases, error cases, boundary values, and null/undefined inputs. Mock external dependencies. Include descriptive test names that explain what's being tested. Aim for >90% branch coverage."
What AI Tests Well
- Pure functions — Input/output testing with various inputs
- Validation logic — Testing all valid and invalid inputs
- Edge cases — Empty arrays, zero values, boundary numbers, special characters
- Error handling — Ensuring errors are thrown and caught correctly
- API response handling — Different response codes, malformed data, timeouts
Workflow: Test-Driven Development with AI
- Describe the function you want to build: inputs, outputs, and behavior
- Ask AI to write the tests first
- Review and adjust the tests to match your requirements
- Ask AI to implement the function that passes all tests
- Run tests and iterate
This TDD approach with AI produces better code than asking AI to write code and tests simultaneously.
Common Pitfalls
- Testing implementation, not behavior — AI sometimes tests internal details. Focus tests on "what does this do?" not "how does this do it?"
- Overmocking — AI tends to mock everything. Only mock external services and slow operations.
- Happy path bias — Explicitly ask for error and edge case tests, or AI will focus on the common path.
- Trusting AI tests blindly — AI can write tests that pass but don't actually verify behavior (e.g., asserting the mock returns what you told it to return).
Explore our Developer Tools prompts for more AI-powered coding workflows.