Code Testing & Unit Test Generation — Guided Lab
Scenario:
You wrote a Python function, but how do you ensure it works correctly in all cases? Manually testing each scenario is tedious. Your AI assistant can generate unit tests and help verify your code automatically.
Step 0: Define Your Goal
Example Python function:
def factorial(n: int) -> int:
if n < 0:
raise ValueError("Input must be non-negative")
result = 1
for i in range(2, n+1):
result *= i
return result
Goal:
- Generate unit tests for valid inputs, edge cases, and invalid inputs
- Make testing repeatable and automated
Step 1: Craft the AI Prompt
Treat AI as a test engineer. Include:
- Your function code
- Instructions to create unit tests for various scenarios
- Optional: use
unittestorpytest
Example Prompt:
Write Python unit tests for the following function using unittest.
Test normal cases, edge cases, and invalid inputs.
Step 2: AI Output Example
import unittest
class TestFactorial(unittest.TestCase):
def test_positive_numbers(self):
self.assertEqual(factorial(5), 120)
self.assertEqual(factorial(3), 6)
def test_zero(self):
self.assertEqual(factorial(0), 1)
def test_negative_numbers(self):
with self.assertRaises(ValueError):
factorial(-1)
if __name__ == '__main__':
unittest.main()
Step 3: Run the Tests
In terminal:
python test_factorial.py
- ✅ All tests pass → your function is correct
- ❌ Any failures → investigate the function or test case
Step 4: Mini Lab Challenges
- Generate unit tests for
is_prime(n)covering all edge cases. - Write tests for
reverse_string(s)including empty strings and invalid types. - Ask AI to create pytest-compatible tests instead of
unittest. - Challenge: generate parameterized tests for multiple inputs automatically.
Step 5: Pro Tips
- Treat AI as a QA engineer, asking it to cover typical, edge, and error cases
- Use AI-generated tests as a starting point, review and expand them
- Test coverage is key — aim to cover all branches of your function
- Iteratively refine prompts to get better, more comprehensive test suites
Lab Summary
- AI can generate automated unit tests, saving time and improving code reliability
- Clear prompts + instructions = high-quality, repeatable tests
- Test first, then refine function or tests based on results
- Combining AI with unit testing improves both learning and production quality






