Automating Unit Test Generation with LLMs for Existing Code
Learn how to use LLMs to automate unit test generation and maintenance in your existing codebase, improving coverage and developer efficiency.
Writing and maintaining unit tests is critical. It is also often tedious, especially in large, established codebases. LLMs can help automate parts of this process. They can generate new tests and assist with maintaining existing ones. This frees up developer time for more complex logic and feature development.
Why Automate Test Generation?
Manual test writing is slow. It can be error-prone. Developers often prioritize new features over comprehensive test suites, especially in older projects. This leads to technical debt and brittle codebases.
LLMs can rapidly generate boilerplate tests. They can suggest edge cases. This improves test coverage faster than manual efforts. For existing code, this means you can start adding tests to untestable areas without a massive upfront time investment.
Generating Tests for Existing Code
Begin by targeting well-defined functions or methods. LLMs perform best when the scope is clear. Provide the LLM with the full source code of the function, including docstrings or comments. These offer valuable context.
Specify the testing framework you use (e.g., pytest, unittest). Tell the LLM what types of tests you need: happy path, edge cases, error handling, input validation. Start simple, then iterate.
Consider this hypothetical Python function:
def calculate_discount(price: float, discount_percentage: float) -> float:
"""
Calculates the final price after applying a discount.
Args:
price: The original price of the item.
discount_percentage: The discount percentage (e.g., 10 for 10%).
Returns:
The final price after discount.
Raises:
ValueError: If price or discount_percentage is negative.
"""
if price < 0 or discount_percentage < 0:
raise ValueError("Price and discount percentage must be non-negative.")
if discount_percentage > 100:
# Cap discount at 100% to avoid negative prices from excessive discount
discount_percentage = 100
discount_amount = price * (discount_percentage / 100)
final_price = price - discount_amount
return round(final_price, 2)
You would prompt the LLM with this code. Request pytest unit tests for normal cases, zero discount, 100% discount, negative inputs (expecting ValueError), and discount percentages over 100.
The LLM might return something like this:
import pytest
from your_module import calculate_discount # Assuming the function is in 'your_module.py'
def test_calculate_discount_normal():
assert calculate_discount(100, 10) == 90.0
assert calculate_discount(50, 25) == 37.5
def test_calculate_discount_zero_discount():
assert calculate_discount(100, 0) == 100.0
def test_calculate_discount_full_discount():
assert calculate_discount(200, 100) == 0.0
def test_calculate_discount_excessive_discount():
# Discount should be capped at 100%
assert calculate_discount(100, 120) == 0.0
def test_calculate_discount_negative_price_raises_error():
with pytest.raises(ValueError, match="Price and discount percentage must be non-negative."):
calculate_discount(-100, 10)
def test_calculate_discount_negative_discount_raises_error():
with pytest.raises(ValueError, match="Price and discount percentage must be non-negative."):
calculate_discount(100, -10)
def test_calculate_discount_zero_price():
assert calculate_discount(0, 50) == 0.0
This provides a solid starting point. Always review generated tests for correctness and completeness. LLMs can hallucinate or miss subtle logic.
Maintaining Tests with LLMs
Test maintenance is a significant overhead. When code changes, tests often break or become outdated. LLMs can assist here too.
Updating Tests: If you modify a function's behavior or signature, provide the LLM with both the old and new function code, plus the existing tests. Ask it to update the tests to reflect the changes. This is faster than manual updates, especially for many affected tests.
Identifying Missing Tests: LLMs can analyze code paths. Prompt them to suggest tests for branches, loops, or error conditions that current tests do not cover. This helps improve overall test coverage incrementally.
Refactoring Tests: Sometimes tests become overly complex or hard to read. You can ask an LLM to refactor existing tests for clarity, using best practices for your chosen framework.
Prompting Strategies for Test Generation
Effective prompting is key to getting useful tests.
- Be Specific: Clearly state the programming language, testing framework, and assertion library. Define the scope of the test (e.g., unit test, integration test).
- Provide Full Context: Include the entire function or class code you want to test. Add any relevant dependencies or helper functions if they are small and critical for context.
- Define Test Scenarios: Outline the types of tests needed: happy path, edge cases (e.g., zero, null, empty string, maximum values), error conditions, performance-critical paths.
- Few-Shot Examples: If you have good examples of existing tests, include one or two in your prompt. This guides the LLM on your preferred style and structure.
- Iterate: Start with a broad request. Then refine by asking for more specific cases or corrections to the generated output. "Add a test for when
discount_percentageis exactly 0." or "Refactor this test to usepytest.approxfor float comparisons."
Integration into CI/CD
Automating test generation is most impactful when integrated into your development workflow. You can use LLMs to suggest tests during code review or pre-commit hooks.
Consider a process where a developer submits a pull request. A CI/CD pipeline could trigger an LLM to analyze new or modified code. The LLM then suggests new unit tests or updates to existing ones. These suggestions appear as comments on the pull request. The developer reviews, accepts, or modifies them before merging.
This approach, often called AI-assisted testing, requires human oversight. Generated tests are not always perfect. They need review to ensure they accurately reflect requirements and catch real bugs. For more on automating code review and testing with generative AI, see our article on /blog/automate-ci-cd-generative-ai-code-review-testing.
Challenges and Considerations
- Hallucinations: LLMs can generate plausible but incorrect tests. They might make wrong assertions or create irrelevant test data. Human review is non-negotiable.
- Context Window Limits: Large files or complex architectural patterns can exceed an LLM's context window. Break down requests into smaller, manageable chunks.
- Test Quality: Generated tests might be basic. They might not cover subtle business logic or complex interactions. They are a starting point, not a complete solution.
- Security and Privacy: Be cautious when sending proprietary or sensitive code to external LLM APIs. Consider local LLMs for highly sensitive projects.
Where to go from here
Start by experimenting with a small, isolated function in your codebase. Focus on generating tests for un-tested components to build confidence in the process. If you need help integrating AI into your development practices, consider our AI consulting services.