Video in progress

Senior 🧪 Testing

You have to change a legacy module that has no tests at all. Where do you start?

First I write characterization tests that "freeze" the current behavior: whatever the code returns now is taken as the expected result. Then, with small, safe refactorings, I open up testable "seams", and only after that do I add the new feature with TDD.

📖 Answer

In legacy code the "correct" behavior is often written down nowhere: it is the code itself. So the first tests check not what "should" be, but what "is".

The steps:

  1. Find the change point. Don't cover the whole module, only the methods you'll touch.
  2. Characterization test. Call the method with different inputs; if you don't know the result, first write assertThat(result).isEqualTo(null), let it fail, and take the real value from the message. For a complex output (a big JSON, a report) use a "golden master": save the result to a file and compare against it on the next run (the ApprovalTests library is built for this).
  3. Open a seam. If the method has new PaymentGateway() or LocalDate.now() inside, move it out to a constructor parameter. This is done with the IDE's automatic refactorings, and the behavior doesn't change.
  4. Now it's testable. For the new feature, TDD: a failing test first, then the code.
@Test
void legacyInvoiceTotalsAreUnchanged() {
    var input = loadJson("legacy/invoice-cases.json", InvoiceRequest[].class);
    var actual = Arrays.stream(input).map(legacyCalculator::calculate).toList();
    JsonApprovals.verifyAsJson(actual);
}

A characterization test "freezes" the bugs too. That's normal: if you find a bug, file it as a separate ticket and change it separately. Don't mix a refactoring and a behavior change in one commit, so that when a test fails you know the reason.

On one project we split a 3000-line calculation class this way in two weeks and not a single calculation changed: the golden master kept comparing 1200 real cases.