10 Prompts for Writing Unit and Integration Tests with AI

10 Prompts for Writing Unit and Integration Tests with AI

Writing tests is often seen as a chore, but it’s one of the most critical activities in software development. Unit tests catch regressions early, integration tests ensure components work together, and both save countless hours in debugging. With the rise of AI code assistants, generating test cases has become faster and more reliable. In this article, I share 10 specific, ready-to-use prompts for generating unit and integration tests using AI tools like GitHub Copilot, ChatGPT, or Claude. Each prompt is explained with its purpose and a concrete usage example.

Why You Need Test Generation Prompts

Modern AI models can generate boilerplate test code in seconds. However, without a well-structured prompt, the output is often too generic or misses edge cases. According to the official pytest documentation, a good test should be readable, isolated, and cover both happy paths and failure scenarios. The prompts below follow these principles and can be adapted for pytest (Python), Jest (JavaScript/TypeScript), and unittest (Python standard library).

Prompt 1: Basic Unit Test for a Pure Function

Task: Generate a unit test for a simple pure function (e.g., a calculator or string utility).

Prompt:

Write a unit test for the following function using pytest. Cover normal cases, edge cases (empty input, negative numbers), and one error case (e.g., division by zero). Use parametrize where possible.

Function:
def divide(a: float, b: float) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

Usage Example:
Paste the prompt into any AI coding assistant. The output will be a test_divide.py file with 3-5 test cases, including @pytest.mark.parametrize for multiple inputs.

Prompt 2: Integration Test with External API Mock

Task: Write an integration test that mocks an external API call (e.g., fetching weather data).

Prompt:

Create an integration test for a function that fetches user data from an external API. Use pytest and the requests-mock library. Mock the API response to return HTTP 200 with a valid JSON, and also test for HTTP 404 and timeout scenarios.

Function signature:
def get_user(user_id: int) -> dict:
    response = requests.get(f"https://api.example.com/users/{user_id}")
    response.raise_for_status()
    return response.json()

Usage Example:
This prompt generates a test that uses requests_mock to simulate different API responses, ensuring your error handling works correctly.

Prompt 3: Database Integration Test with SQLAlchemy

Task: Generate a test that interacts with a real or in-memory database.

Prompt:

Write an integration test for a CRUD function using SQLAlchemy and an in-memory SQLite database. Test creating a new record, reading it, updating it, and deleting it. Use pytest fixtures to set up and tear down the database session.

Function to test:
def create_user(db_session, name: str, email: str) -> User:
    user = User(name=name, email=email)
    db_session.add(user)
    db_session.commit()
    return user

Usage Example:
The AI will output a conftest.py with a fixture for db_session and a test function that verifies the user is correctly created and retrieved.

Prompt 4: Async Unit Test with pytest-asyncio

Task: Write a test for an async function.

Prompt:

Write a unit test for an async function that calls an external service. Use pytest-asyncio to handle async fixtures and tests. Mock the external service call.

Async function:
async def fetch_price(symbol: str) -> float:
    async with httpx.AsyncClient() as client:
        response = await client.get(f"https://api.market.com/price/{symbol}")
        return response.json()["price"]

Usage Example:
This prompt is perfect for testing async code in Python. The AI will generate a test with @pytest.mark.asyncio and a mock for httpx.AsyncClient.

Prompt 5: Jest Unit Test for a React Component

Task: Generate a Jest test for a React functional component.

Prompt:

Write a Jest unit test for a React component that displays a list of items. Use @testing-library/react. Test that the component renders the list correctly when passed an array, renders an empty state when array is empty, and shows a loading spinner while data is being fetched.

Component:
function ItemList({ items, isLoading }) {
  if (isLoading) return <div data-testid="loading">Loading...</div>;
  if (items.length === 0) return <div data-testid="empty">No items</div>;
  return (
    <ul>
      {items.map(item => <li key={item.id}>{item.name}</li>)}
    </ul>
  );
}

Usage Example:
The AI will output a ItemList.test.js file with render, screen.getByTestId, and assertions for all three states.

Prompt 6: Integration Test for a REST API Endpoint

Task: Write an integration test that starts a test server and calls an endpoint.

Prompt:

Create an integration test for a Flask REST API endpoint using pytest and the test client. Test POST /users with valid data (status 201), missing fields (status 400), and duplicate email (status 409).

Endpoint:
@app.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    if 'email' not in data:
        return jsonify({"error": "Email required"}), 400
    # logic to create user

Usage Example:
The prompt yields a test using app.test_client() and multiple assert statements for each HTTP status code.

Prompt 7: Edge Case Coverage for a Sorting Algorithm

Task: Generate a test suite for a custom sorting function, covering edge cases.

Prompt:

Write a comprehensive unit test suite for a custom merge sort implementation using pytest. Include tests for: already sorted list, reverse sorted list, list with duplicates, single element, empty list, and list with negative numbers. Use parametrize.

Function:
def merge_sort(arr: list) -> list:
    # implementation

Usage Example:
The AI will generate 6 test cases, all parametrized, ensuring your sorting algorithm is robust.

Prompt 8: Mocking External Services in Node.js

Task: Write a Jest test that mocks a third-party module (e.g., axios).

Prompt:

Write a Jest test for a function that sends an email via a third-party service. Mock the axios module to simulate successful and failed email sending. Use jest.mock for the module.

Function:
const sendEmail = async (to, subject, body) => {
  await axios.post('https://api.emailservice.com/send', { to, subject, body });
};

Usage Example:
The prompt will generate a test with jest.mock('axios') and two test cases: success and network error.

Prompt 9: Test Fixtures and Setup/Teardown

Task: Generate a pytest fixture for a complex object (e.g., a database connection or a web driver).

Prompt:

Create a pytest fixture that sets up a temporary SQLite database, populates it with sample data, and tears it down after each test. Use scope='function'. Then write a test that queries the database.

Database schema:
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL);

Usage Example:
The AI will output a fixture that creates a database file in tmp_path and a test that inserts and queries products.

Prompt 10: Integration Test with Docker Compose

Task: Generate an integration test that requires a running Docker container (e.g., PostgreSQL).

Prompt:

Write an integration test in Python that connects to a PostgreSQL database running in a Docker container using testcontainers-python. Test inserting a record and reading it back. Use pytest fixtures for container lifecycle.

Function to test:
def save_user(conn, user: dict) -> int:
    cursor = conn.cursor()
    cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id", (user['name'], user['email']))
    conn.commit()
    return cursor.fetchone()[0]

Usage Example:
This advanced prompt leverages the testcontainers library to spin up a real PostgreSQL container, run tests, and shut it down automatically.

Conclusion

These 10 prompts cover a wide range of testing scenarios, from simple unit tests to complex integration tests with external dependencies. Whether you use pytest, Jest, or unittest, adapting these prompts to your specific framework is straightforward. The key is to be explicit about the expected behavior, edge cases, and mocking strategy. By incorporating these prompts into your workflow, you can significantly accelerate test generation and improve code quality.

Remember, AI-generated tests are a starting point — always review and run them to ensure they match your business logic. Happy testing!

← All posts

Comments