How-To Guide

How to Write Characterization Tests

Pin down the current behaviour of legacy code with tests that record what it does, so you can refactor safely.

On this page

  1. Introduction
  2. The Legacy Code Problem
  3. Recording Current Behaviour
  4. Reducing the Space of Inputs
  5. Handling Output You Cannot Assert Directly
  6. Using the Tests to Refactor
  7. Retiring and Maintaining Them
  8. Conclusion

Introduction

Legacy code is code that works and nobody dares change, usually because it has no tests and its behaviour is not fully understood. You cannot refactor it safely without a net, and you cannot write a net if you do not know what correct looks like. Characterization tests solve the bootstrapping problem: instead of asserting what the code should do, they assert what it does, recording its current behaviour so that any future change that alters it fails loudly. This article explains how to write them, how to handle output you cannot assert directly, and how to retire them as real tests replace them.

The Legacy Code Problem

You inherit a function that computes a price, has no tests, and is called from eleven places. You need to change it. You do not know which of its behaviours are intentional and which are accidents, and you cannot ask the original author. Any change risks breaking a caller that depends on a quirk you did not know existed. This is the situation characterization tests are for.

The insight is that you do not need to know what the code should do to protect what it currently does. Record the current output for a set of inputs, and any change to that output becomes a signal that you must consciously accept or reject. The tests are not a specification; they are a change detector.

Recording Current Behaviour

Write a test that calls the code with representative inputs and asserts the exact current output, even when that output looks wrong. Run it once to see the actual values, then paste them into the assertion. If the output is wrong, do not fix it in the same step; record it, because the goal now is to lock the behaviour so you can change structure without changing behaviour.

// Characterization test: locks the CURRENT output, bugs included.
describe('calculateOrderTotal (characterization)', () => {
  it('matches current behaviour for a simple order', () => {
    const result = calculateOrderTotal({ items: [{ price: 1000, qty: 2 }] });
    // Recorded from the current implementation, not from the spec.
    expect(result).toEqual({ subtotal: 2000, tax: 0, total: 2000 });
  });

  it('matches current behaviour when quantity is zero', () => {
    const result = calculateOrderTotal({ items: [{ price: 1000, qty: 0 }] });
    // Current code returns a negative total here; record it as-is.
    expect(result).toEqual({ subtotal: 0, tax: 0, total: 0 });
  });
});

Reducing the Space of Inputs

A characterization test is only as useful as its input coverage, but you cannot test every input. Use the inputs the code is called with in production: query logs, sample real records, or instrument the function to record its arguments for a day. Then pick the interesting cases: boundaries, empty inputs, the value that caused the last incident. Those inputs will expose the behaviours your change is likely to disturb.

When a function depends on external state, such as the current time, randomness, or a database, pin that state so the recorded output is stable. Capture-and-replay is the pragmatic approach: record the external responses once and replay them in the test, instead of trying to construct them. This is closely related to why tests need a deterministic clock.

Handling Output You Cannot Assert Directly

Some code produces output that is hard to assert: a timestamp, a generated identifier, a large object, a log line. Assert the parts that are stable and ignore the parts that are not, or normalize the output before comparing. For a generated id, assert its shape rather than its value. For a large object, compare a canonical serialization or a hash. For a timestamp, freeze the clock so it becomes deterministic.

For very complex output, store it as a golden or snapshot file and compare against the file. Review the snapshot diff by hand so an accidental change is caught rather than approved blindly. A snapshot you never read is just a test that always passes.

// Normalize volatile fields so the assertion is stable but still meaningful.
function normalizeReceipt(receipt) {
  return {
    ...receipt,
    id: '<generated>',              // assert the shape, not the value
    createdAt: '<generated>',
    total: receipt.total,           // the value we actually care about
  };
}

it('matches current receipt shape (characterization)', () => {
  const receipt = buildReceipt({ items: [{ price: 1000, qty: 2 }] });
  expect(normalizeReceipt(receipt)).toEqual({
    id: '<generated>',
    createdAt: '<generated>',
    total: 2000,
    currency: 'USD',
  });
  // For a large body, compare against a golden file instead:
  // expect(normalizeReceipt(receipt)).toMatchSnapshot();
});

Using the Tests to Refactor

With behaviour pinned, refactor in small steps, running the characterization tests after each. Because the tests assert current behaviour, a failure means you changed behaviour, not that you improved the structure. When the refactor is done and the tests still pass, you have changed the shape without changing what the code does, which is exactly the safe refactor you wanted.

Once the structure allows it, write real tests for the behaviour you now understand, asserting what the code should do rather than what it does. Replace the characterization tests with them, one at a time, so the test suite moves from describing the past to specifying the future. Do not delete a characterization test until its replacement is passing.

Retiring and Maintaining Them

Characterization tests are scaffolding, not the finished building. They should shrink over time as real tests take their place. If they stay forever, they lock in bugs and make intentional changes look like regressions. Track which characterization tests you have replaced and delete them deliberately.

When you do accept a behaviour change, update the characterization test in the same commit and say so, so the change is explicit in the diff. A characterization test that is updated casually, without noting why, has stopped functioning as a change detector. Treat each update as a deliberate decision that the new behaviour is intentional.

Conclusion

Characterization tests let you change legacy code without a specification by locking its current behaviour first. Record exact outputs for representative inputs, pin external state so they are stable, normalize or snapshot output you cannot assert directly, and refactor in small steps with the tests as your net. Then replace them with real tests as you learn what the code should do, and delete each characterization test only after its replacement passes. Scaffolding that comes down is as valuable as scaffolding that goes up.

Sources: Working Effectively with Legacy Code (Feathers), Characterization test (Martin Fowler), Golden master testing.

FAQ

Should a characterization test assert correct behaviour or current behaviour?
Current behaviour, even when it looks wrong. The purpose is to detect any change so you can decide consciously whether it is intentional. Fixing a bug and locking behaviour are separate steps; doing both at once defeats the safety net.
When should I delete a characterization test?
After a real test that specifies the intended behaviour for the same case is passing. Replacing them one at a time moves the suite from describing the past to specifying the future, and avoids locking in bugs indefinitely.

Related Examples