15 Prompts for Writing Unit and Integration Tests
Introduction
Writing tests is one of the most effective ways to ensure code reliability and prevent regressions. Yet many developers struggle to get started or write tests that actually catch bugs. Large codebases with poor test coverage often lead to broken deployments, frustrated teams, and technical debt. According to the 2023 Stack Overflow Developer Survey, over 70% of professional developers write tests regularly, but the quality of those tests varies widely.
This guide provides 15 ready-to-use prompts for generating unit and integration tests with popular frameworks like pytest (Python), Jest (JavaScript), and unittest (Python). Each prompt is specific, copy-paste ready, and includes a usage example. Whether you are a beginner learning test-driven development or an experienced engineer looking to speed up your workflow, these prompts will help you produce maintainable, thorough tests.
Why Use Prompts for Test Generation?
Prompt engineering for code generation has become a standard practice. Instead of manually typing boilerplate test cases, you can describe the function or module and the AI generates the test suite. This approach saves time, reduces human error, and ensures consistency. For example, a prompt like "Write pytest tests for a function that validates email addresses" produces a complete test file with edge cases, parameterized tests, and fixtures.
Prompt 1: Basic pytest Unit Test for a Function
Task: Generate a unit test for a simple mathematical function.
Prompt:
Write a pytest unit test for the following Python function:
def add(a, b):
return a + b
Include tests for positive numbers, negative numbers, zero, and floating point values. Use parameterized tests.
Usage Example:
import pytest
from mymodule import add
@pytest.mark.parametrize("a,b,expected", [
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0),
(1.5, 2.5, 4.0),
])
def test_add(a, b, expected):
assert add(a, b) == expected
Prompt 2: Jest Unit Test for a JavaScript Function
Task: Generate a Jest test for a string utility.
Prompt:
Write a Jest test for the following JavaScript function:
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
Include tests for empty string, single character, and already capitalized string.
Usage Example:
const capitalize = require('./utils');
test('capitalize works correctly', () => {
expect(capitalize('hello')).toBe('Hello');
expect(capitalize('')).toBe('');
expect(capitalize('a')).toBe('A');
expect(capitalize('World')).toBe('World');
});
Prompt 3: unittest Test Suite for a Class
Task: Generate a unittest test case for a Python class with multiple methods.
Prompt:
Write a Python unittest test case for the following class:
class Calculator:
def add(self, a, b): return a + b
def subtract(self, a, b): return a - b
def multiply(self, a, b): return a * b
def divide(self, a, b): return a / b
Include setup method, tests for each operation, and test for division by zero (expecting ZeroDivisionError).
Usage Example:
import unittest
from calculator import Calculator
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_add(self):
self.assertEqual(self.calc.add(3, 4), 7)
def test_subtract(self):
self.assertEqual(self.calc.subtract(10, 5), 5)
def test_multiply(self):
self.assertEqual(self.calc.multiply(3, 4), 12)
def test_divide(self):
self.assertEqual(self.calc.divide(10, 2), 5)
def test_divide_by_zero(self):
with self.assertRaises(ZeroDivisionError):
self.calc.divide(10, 0)
if __name__ == '__main__':
unittest.main()
Prompt 4: Integration Test with pytest and Database
Task: Generate an integration test that interacts with a real database.
Prompt:
Write a pytest integration test for a function that inserts a user into a PostgreSQL database. Use a test fixture to create and drop a temporary table. The function signature: def create_user(conn, username, email).
Usage Example:
import pytest
import psycopg2
from mydb import create_user
@pytest.fixture
def db_connection():
conn = psycopg2.connect("dbname=test user=test password=test")
yield conn
conn.close()
@pytest.fixture
def setup_table(db_connection):
cur = db_connection.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, username TEXT, email TEXT)")
yield
cur.execute("DROP TABLE IF EXISTS users")
db_connection.commit()
def test_create_user(db_connection, setup_table):
create_user(db_connection, "alice", "alice@example.com")
cur = db_connection.cursor()
cur.execute("SELECT username, email FROM users")
result = cur.fetchone()
assert result == ("alice", "alice@example.com")
Prompt 5: Mock External API Call in Jest
Task: Generate a Jest test that mocks an HTTP request.
Prompt:
Write a Jest test for a function that fetches user data from an external API. Mock the fetch call to return a fake response. The function: async function getUser(id) { const res = await fetch(`/api/users/${id}`); return res.json(); }
Usage Example:
const { getUser } = require('./api');
test('getUser returns user data', async () => {
const fakeUser = { id: 1, name: 'John' };
global.fetch = jest.fn(() =>
Promise.resolve({ json: () => Promise.resolve(fakeUser) })
);
const user = await getUser(1);
expect(user).toEqual(fakeUser);
expect(fetch).toHaveBeenCalledWith('/api/users/1');
});
Prompt 6: Test Edge Cases for Input Validation
Task: Generate tests that cover edge cases like None, empty strings, and special characters.
Prompt:
Write pytest tests for a function that validates a username: must be 3-20 characters, alphanumeric only. Include tests for valid, too short, too long, invalid characters, and empty string.
Usage Example:
import pytest
from validation import validate_username
def test_valid_username():
assert validate_username("john_doe") == True
def test_too_short():
assert validate_username("ab") == False
def test_too_long():
assert validate_username("a" * 21) == False
def test_invalid_characters():
assert validate_username("hello world") == False
def test_empty_string():
assert validate_username("") == False
Prompt 7: Asynchronous Test with pytest-asyncio
Task: Generate a test for an async function.
Prompt:
Write a pytest test using pytest-asyncio for an async function that fetches data from a database. Use an in-memory SQLite database and a fixture that creates tables.
Usage Example:
import pytest
import aiosqlite
from mymodule import async_get_user
@pytest.fixture
async def db():
async with aiosqlite.connect(":memory:") as db:
await db.execute("CREATE TABLE users (id INT, name TEXT)")
await db.execute("INSERT INTO users VALUES (1, 'Alice')")
yield db
@pytest.mark.asyncio
async def test_async_get_user(db):
user = await async_get_user(db, 1)
assert user == (1, "Alice")
Prompt 8: Test HTTP Endpoint with FastAPI TestClient
Task: Generate an integration test for a FastAPI endpoint.
Prompt:
Write a pytest test using FastAPI's TestClient to test a POST /items endpoint that accepts JSON and returns the created item.
Usage Example:
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_create_item():
response = client.post("/items", json={"name": "Laptop", "price": 1200})
assert response.status_code == 200
data = response.json()
assert data["name"] == "Laptop"
assert data["price"] == 1200
Prompt 9: Test File I/O Operations with Temporary Files
Task: Generate tests for a function that reads/writes files.
Prompt:
Write pytest tests for a function that writes a list of strings to a file and another that reads them back. Use tmp_path fixture.
Usage Example:
import pytest
from fileutils import write_lines, read_lines
def test_write_and_read(tmp_path):
d = tmp_path / "sub"
d.mkdir()
file_path = d / "test.txt"
lines = ["line1", "line2", "line3"]
write_lines(file_path, lines)
result = read_lines(file_path)
assert result == lines
Prompt 10: Test Exception Handling and Error Messages
Task: Generate tests that verify exceptions are raised with correct messages.
Prompt:
Write pytest tests for a function that raises ValueError with specific messages for invalid inputs. The function: def set_age(age): if age < 0: raise ValueError("Age cannot be negative"); if age > 150: raise ValueError("Age cannot exceed 150")
Usage Example:
import pytest
from person import set_age
def test_negative_age():
with pytest.raises(ValueError, match="Age cannot be negative"):
set_age(-1)
def test_age_too_high():
with pytest.raises(ValueError, match="Age cannot exceed 150"):
set_age(151)
def test_valid_age():
set_age(30) # should not raise
Prompt 11: Parameterized Integration Test with Multiple Scenarios
Task: Generate a parameterized test that runs the same integration scenario with different inputs.
Prompt:
Write a pytest parameterized integration test for an API endpoint that calculates shipping cost. Use a fixture to set up the test server. Test with different weights and destinations.
Usage Example:
import pytest
@pytest.mark.parametrize("weight, destination, expected_cost", [
(1, "US", 5.0),
(10, "US", 15.0),
(1, "EU", 8.0),
])
def test_shipping_cost(api_client, weight, destination, expected_cost):
response = api_client.post("/shipping", json={"weight": weight, "destination": destination})
assert response.json()["cost"] == expected_cost
Prompt 12: Test Database Transactions and Rollback
Task: Generate a test that verifies database transactions correctly roll back on error.
Prompt:
Write a pytest test for a function that updates two tables in a single transaction. If the second update fails, the first should roll back.
Usage Example:
@pytest.mark.asyncio
async def test_transaction_rollback(async_db):
async with async_db.transaction():
await async_db.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
# Simulate failure
raise RuntimeError("something went wrong")
# Check that balance didn't change
balance = await async_db.fetchval("SELECT balance FROM accounts WHERE id = 1")
assert balance == 1000 # original value
Prompt 13: Test Configuration and Environment Variables
Task: Generate a test that checks if the application reads environment variables correctly.
Prompt:
Write a pytest test that uses monkeypatch to set environment variables and verify that a config module returns the expected values.
Usage Example:
import pytest
from config import get_api_key
def test_api_key_from_env(monkeypatch):
monkeypatch.setenv("API_KEY", "test123")
assert get_api_key() == "test123"
Prompt 14: Test Performance and Timeouts
Task: Generate a test that ensures a function completes within a time limit.
Prompt:
Write a pytest test with a timeout marker to verify that a slow function returns within 2 seconds.
Usage Example:
import pytest
@pytest.mark.timeout(2)
def test_fast_enough():
result = slow_function()
assert result == expected
Prompt 15: Test Logging and Side Effects
Task: Generate a test that verifies that a function logs a specific message.
Prompt:
Write a pytest test using caplog fixture to check that a function logs a warning when input is empty.
Usage Example:
import pytest
import logging
from mymodule import process_input
def test_logs_warning(caplog):
caplog.set_level(logging.WARNING)
process_input("")
assert "Empty input provided" in caplog.text
Conclusion
Using prompts to generate unit and integration tests can significantly accelerate your development workflow. The 15 prompts above cover a wide range of scenarios: from simple function tests to complex integration tests with databases, APIs, and asynchronous code. For each prompt, you can adjust the function names, parameters, and expected results to match your project.
Remember that prompt quality directly affects test quality. Be specific about the function signature, expected behavior, and edge cases. If you are working with a large codebase, consider using a tool like ASI Biont that supports connecting to various services via API — for more details, visit asibiont.com/courses. With practice, you will be able to generate robust, comprehensive test suites in minutes.
Comments