pexels-ron-lach-9783346
by 
19 Oct/25

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:

  1. Your function code
  2. Instructions to create unit tests for various scenarios
  3. Optional: use unittest or pytest

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

  1. Generate unit tests for is_prime(n) covering all edge cases.
  2. Write tests for reverse_string(s) including empty strings and invalid types.
  3. Ask AI to create pytest-compatible tests instead of unittest.
  4. 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

Leave A Comment

Cart (0 items)
Proactive is a Digital Agency WordPress Theme for any agency, marketing agency, video, technology, creative agency.
380 St Kilda Road,
Melbourne, Australia
Call Us: (210) 123-451
(Sat - Thursday)
Monday - Friday
(10am - 05 pm)