12 Prompts for Writing Bulletproof Unit and Integration Tests (pytest, Jest, unittest)
Testing is the safety net of software development, yet many developers put it off because writing tests feels tedious. Large language models (LLMs) can flip that: with the right prompt, you can generate robust test suites in seconds. This guide gives you 12 battle-tested prompts for pytest, Jest, and unittest — each with a concrete example and expert commentary. Use them to speed up your TDD workflow, improve coverage, and catch more bugs.
Why Specific Prompts Matter
A vague prompt like "write tests" yields generic results. A detailed prompt — with framework, function signature, edge cases, and expected behavior — produces focused, production-ready tests. The examples below follow the format: prompt → AI-generated output → why it works. All prompts were tested with GPT-4-class models in real repos.
Pytest Prompts
1. Generate a Test Suite for a Pure Function
Prompt: Act as a senior Python developer. Write a complete pytest test suite for the function below. Cover normal cases, edge cases (empty input, None, very large values), and expected exceptions. Use descriptive test names and keep tests independent.
Example function:
def calculate_discount(price, percent):
if price <= 0:
raise ValueError("Invalid price")
return price * (1 - percent/100)
AI-generated test:
def test_discount_normal():
assert calculate_discount(100, 10) == 90
def test_invalid_price_raises():
with pytest.raises(ValueError):
calculate_discount(0, 10)
Why it works: The prompt explicitly asks for edge cases and exceptions, turning a trivial function into a tested one.
2. Use Fixtures for Database Setup
Prompt: Create pytest fixtures that set up a test database and tear it down after each test. Use a fixture for the database connection and another for a sample user.
AI-generated fixture:
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
yield conn
conn.close()
Why it works: Fixtures avoid code duplication and make tests isolated.
3. Parametrize Tests for Edge Cases
Prompt: Rewrite these test functions as parametrized tests in pytest, with at least 5 cases covering boundaries and invalid inputs.
AI-generated parameter set:
@pytest.mark.parametrize("input,expected", [
(0, 0), (1, 1), (10, 10), (-1, None), (1000, 1000)
])
Why it works: Parametrization removes boilerplate and forces the model to think about boundary values.
4. Mock External API Calls
Prompt: Write a pytest test for a function that calls requests.get(). Use monkeypatch to mock the response and verify error handling for HTTP 500.
AI-generated test:
def test_api_error(monkeypatch):
class FakeResponse:
status_code = 500
monkeypatch.setattr(requests, "get", lambda url: FakeResponse())
with pytest.raises(ApiError):
fetch_data("https://api.example.com")
Why it works: Explicitly naming the mocking technique gives deterministic, network-free tests.
5. Integration Test with a Real Database
Prompt: Write an integration test in pytest that uses a real PostgreSQL test database. The test should insert a record, retrieve it, and clean up. Use a fixture marked as integration.
AI-generated fixture:
@pytest.fixture
@pytest.mark.integration
def db_conn():
conn = psycopg2.connect("dbname=test")
yield conn
conn.close()
Why it works: It separates slow integration tests from fast unit tests via markers.
6. Send a Coverage Report
Prompt: Show the pytest command to measure coverage with pytest-cov and generate an HTML report with a threshold of 85%.
AI-generated command:
pytest --cov=my_module --cov-report=html --cov-fail-under=85
Why it works: This prompt directly produces an actionable CI command.
Jest Prompts
7. Test a React Component
Prompt: You are an expert in React testing. Write Jest + React Testing Library tests for this component. Test rendering, user interactions, and accessibility with jest-dom.
AI-generated test:
it("increments counter on click", () => {
render(<Counter />);
fireEvent.click(screen.getByRole("button"));
expect(screen.getByText("1")).toBeInTheDocument();
});
Why it works: It asks for both behavior and accessibility checks, aligning with modern testing standards.
8. Snapshot Test a Component
Prompt: Generate a Jest snapshot test for this component and explain when snapshots are appropriate. Include a test that checks the component's appearance.
AI-generated test:
it("matches snapshot", () => {
const { asFragment } = render(<Button>Click</Button>);
expect(asFragment()).toMatchSnapshot();
});
Why it works: Snapshot tests are useful for UI regression, and the prompt guides the model to use asFragment correctly.
9. Integration Test an Express API
Prompt: Write an integration test for an Express API using Jest and supertest. Test POST /users and GET /users/:id, including validation errors.
AI-generated test:
it("creates a user", async () => {
const res = await request(app)
.post("/users")
.send({ name: "John" });
expect(res.status).toBe(201);
});
Why it works: Supertest is the standard tool for HTTP integration tests, and the prompt mentions validation errors, so the model adds negative cases.
unittest Prompts
10. Test a Python Class
Prompt: Write unittest tests for this Python class. Use setUp and tearDown, and test the methods with different inputs using assertEqual and assertRaises.
AI-generated test:
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_add(self):
self.assertEqual(self.calc.add(2, 3), 5)
def test_divide_by_zero(self):
with self.assertRaises(ZeroDivisionError):
self.calc.divide(1, 0)
Why it works: The prompt mentions specific unittest methods, so the output follows the framework's conventions.
Cross-Cutting Prompts
11. Mock External Dependencies in unittest
Prompt: Write a unittest test for a class that sends email via smtplib. Mock SMTP and assert that sendmail is called once with the correct arguments.
AI-generated code:
@patch("smtplib.SMTP")
def test_send_email(self, mock_smtp):
messenger.send("a@b.com", "Hi")
mock_smtp.return_value.sendmail.assert_called_once()
Why it works: Mocking external services is a critical skill; this prompt targets a common real-world scenario.
12. Generate a Test Plan for a User Story
Prompt: Act as a QA architect. Create a test plan for this user story: "As a user, I can reset my password via email." List unit and integration test cases, edge cases, and success criteria.
AI-generated plan (shortened):
- Unit: validate email format, generator creates non-empty token, token expires.
- Integration: /api/reset sends email, /api/reset/confirm updates password.
- Edge: unknown email returns 200 (security), token reused after reset.
Why it works: It shifts from implementation to strategy, useful for TDD planning.
Conclusion
These 12 prompts are a starting point. Experiment with them, adjust the wording, and always review the generated tests — AI is powerful, but human judgment for edge cases and security is irreplaceable. For further reading, check the official documentation: pytest, Jest, and unittest. Start using one prompt today, and watch your test suite grow.
Comments