What Are Characterization Tests
You'll learn: How to use characterization tests to safely document the current behavior of legacy code before making changes.
The Documentation Challenge in Legacy Code
When you inherit legacy code without tests, you face a dangerous dilemma: you need to understand what the code actually does before you can safely change it. This is where characterization tests come in—they're tests you write not to verify correctness, but to capture and document the code's existing behavior, warts and all.
Think of characterization tests like taking a "before" photograph before renovating a house. You're not judging whether the current state is good or bad—you're simply recording what's there so you can detect any unintended changes.
How Characterization Tests Work
Unlike traditional tests where you know the expected behavior upfront, characterization tests follow a discovery process:
- Write a test that exercises the legacy code with specific inputs
- Let it fail to see what the actual output is
- Record that output as the expected result in your test
- Run the test again—it should now pass
You're essentially asking the code "What do you do?" rather than "Do you do what I think you should?"
These tests become your safety net. When you refactor, they'll tell you if you've accidentally changed behavior. They preserve the current functionality while you improve the structure, addressing the legacy code dilemma you learned about earlier.
When to Use Them
Characterization tests are invaluable when you're working at a seam in legacy code and need confidence that your changes preserve existing behavior—even if that behavior includes bugs that users may have come to depend on.
Key Takeaway: Characterization tests document existing behavior as-is, creating a safety net that detects unintended changes during refactoring of legacy code.