Skip to the content.

Characterization tests

A characterization test records what the code does, not what it should do. It is a safety net for change, not a specification.

Steps

  1. Pick the seam. The narrowest public entry point that exercises the code you will change: a function, a CLI command, an HTTP endpoint, a report generator.
  2. Generate inputs that cover the branches: read the code and list conditions; create inputs for each side of each condition, plus real-world samples (anonymized production payloads, fixtures from bug reports). For combinatorial inputs, generate the cross product of a few values per parameter.
  3. Capture outputs. Call the code with each input and record the output (return value, written file, HTTP response, SQL emitted). Normalize unstable parts first: timestamps, random IDs, ordering of sets/maps, absolute paths.
  4. Write the tests asserting outputs equal the recorded ones. Options:
    • Snapshot/approval tools in the existing stack (Jest/Vitest snapshots, pytest snapshot plugins, approval-test libraries).
    • Plain golden files: tests/golden/<case>.json plus a test that compares, and an UPDATE_GOLDEN=1 switch to regenerate.
  5. Check they bite. Make a small deliberate change in the code and confirm at least one test fails.
  6. Mark surprises. When recorded behavior looks wrong, keep the test as-is (it documents reality) and add a comment # characterization: looks like a bug, see <issue>. Fixing it is a separate, explicit change.

Then change the code

Refactor with the tests green after every step. When you intentionally change behavior, update only the affected golden outputs and explain each change in the commit.

Clean up later

Once real, intention-revealing unit tests exist for the area, delete characterization tests that duplicate them; golden files rot if nobody understands them.