Pattern 14: Test-After Development

Using AI to Write Comprehensive Tests for Existing Code

Overview

Test-after development adds comprehensive tests to existing code, making it safe to change.

Why do this?

  • You’ve inherited code that’s too risky to change
  • You need confidence before refactoring
  • You want to prevent regressions in critical logic
  • AI excels at this tedious work

This pattern is vital for legacy systems and acquired codebases. AI can quickly build safety nets around existing functionality.

Key Principles

  1. Preserve behavior - Test what is, not what should be
  2. Strategic coverage - Critical paths and edges first
  3. Incremental safety - Each test enables next change
  4. Prevent regression - Lock in existing features

Exercise: Add Safety Net to PlantAutopsy

Your Pattern 1 prototype had zero tests. Add comprehensive tests to make it safe to change.

Steps:

  1. Understand behavior: Give AI your original code. Ask: “What are all code paths, edge cases, and inputs?”

  2. Generate tests: Ask AI: “Create comprehensive tests. Include happy path, edge cases, malformed inputs.”

  3. Verify: Run tests. Check coverage. Break code to verify tests fail. Refine with AI until robust.

  4. Dig: Look carefully for tests that are not-functional test and are testing existing behavior that is not intended behavior.

Your Turn

Find a small open-source project that lacks tests. Use AI to write comprehensive tests for one module and submit them as a pull request.

Don’t Push Slop

Don’t just have AI submit the tests as a pull request. Review the tests and make sure they are correct and be thorough. This is an opportunity to learn how to review AI code.

You are responsible for every line of code you provide to someone else. If you don’t review or understand the code, keep going until you understand it before submitting it. Explain why you made the changes you did and why you think those tests are helpful.