Java · Intermediate level

Intermediate level · Module 5: Unit Testing with JUnit 5 · Lesson 3 of 3

Tests as a Safety Net: Bugs and Refactoring

Reproduce a reported bug with a failing test, fix it, and use the test suite to change code structure without changing behaviour.

In this lesson you will

  • Write a regression test that reproduces a bug before fixing it
  • Refactor code with the test suite as a safety net

Key concepts

regression testred–green–refactorrefactoringtest coverage

The lesson

When a bug is reported, first write a test that fails because of it. Then fix the code until the test passes. The test stays in the suite, so the same bug can never come back unnoticed — that is why it is called a regression test.

Refactoring changes the structure of code without changing what it does: renaming, extracting methods, removing duplication. With good tests, you can refactor confidently, because any change in behaviour turns a test red.

Coverage tools show which lines your tests run. High coverage is useful, but it does not prove the tests check the right things; a test with no meaningful assertions covers lines while testing nothing.

Step by step

  1. Read a bug report about overdue loans being calculated one day late.
  2. Write a failing test that reproduces it.
  3. Fix the code and run the whole suite.
  4. Extract a method to remove duplicated date logic, running tests after each step.

Practice activity

Find and fix the two seeded bugs in the provided library code, writing a regression test for each before fixing it.

Expected result: Two new tests that failed before the fixes now pass, together with the rest of the suite.

Check your understanding

  1. Why write the failing test before fixing a bug?

    Show answer

    It proves the bug is reproduced and that the fix works, and it prevents the bug returning.

  2. What must not change during refactoring?

    Show answer

    The program's behaviour.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.