Skip to content

Regression Tests

The Course
•
15 min study

A regression test keeps an already-fixed bug from returning unnoticed. Pick cases that distinguish the intended behavior from a plausible mistake. Test the public contract and the state after rejection, rather than copying an implementation line by line.

Work through the example

The parser accepts inclusive boundaries. The rejection helper throws AssertionError if a supposedly invalid input is accepted. Catching only IllegalArgumentException prevents the helper from swallowing its own failure. Labels in assertion messages help identify the failing case.

Tests are executable examples of the contract. A positive example proves one path; a boundary or rejection case challenges another. Neither proves all possible inputs, so choose a small set based on decisions the code makes: shape, conversion, range and duplicate identity.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        check("minimum", parse("1") == 1);
        check("maximum", parse("240") == 240);
        reject("0");
        reject("241");
        reject("nope");
        System.out.println("Parser checks passed");
    }

    static int parse(String text) {
        int value = Integer.parseInt(text);
        if (value < 1 || value > 240) {
            throw new IllegalArgumentException("outside range");
        }
        return value;
    }

    static void reject(String text) {
        try {
            parse(text);
            throw new AssertionError("accepted " + text);
        } catch (IllegalArgumentException expected) {
            // Expected parser rejection, not any possible failure.
        }
    }

    static void check(String label, boolean condition) {
        if (!condition) {
            throw new AssertionError(label);
        }
    }
}
Check your prediction
Text
Parser checks passed

Compare the behavior

List.of("Read") is a convenient library factory for an unmodifiable list. It rejects null elements. Here it supplies a fixed expected value; we do not try to edit it.

A test needs an independent expectation. Computing expected by calling the same implementation again would repeat its defect. This example checks that a snapshot still contains Read after its source is cleared, comparing it with a fixed expected list. Changing the input after the call also checks whether a returned result shares state unintentionally.

Trace the changed case Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>();
        source.add("Read");
        List<String> snapshot = new ArrayList<>(source);
        source.clear();
        if (!snapshot.equals(List.of("Read"))) {
            throw new AssertionError("snapshot changed with source");
        }
        System.out.println("Snapshot isolated");
    }
}
Check your prediction
Text
Snapshot isolated

Name the plausible defect each check detects

A regression case is useful because it distinguishes correct behavior from a specific mistake. Testing 240 protects an inclusive upper bound. Testing a duplicate ID protects preservation of the first stored value. Clearing a returned snapshot protects ownership. Give each check a name describing that promise.

A rejection test must fail when no exception is thrown. Put AssertionError after the call and catch only the expected input rejection. If the call returns normally, the assertion should escape rather than enter a catch that calls the case successful. Then inspect state after rejection when the operation could have changed it.

Mutation practice tests the strength of these observations. Remove one guard or reverse one comparison, run the same tests and record the failed label. Restore the baseline before another mutation. A syntax error does not establish that a behavioral assertion detected the intended defect.

Practice independently

Exercise

Regression Tests: practice

A user reported: "I added task A1 again by mistake. I got an error, which is fine, but my original A1 title was gone." Someone has already fixed it. Your job is the regression test: a check that fails on the old code and passes on the fix, so the bug cannot quietly return.

The workspace contains both versions behind one Store interface. Write keepsOriginalAfterDuplicate(Store store): add A1/Read, try to add A1/Lost, expect the rejection, and return whether find("A1") is still Read. Main runs your test against both versions:

Text
old: false
fixed: true
Your workspace Java
import java.util.Map;
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        System.out.println("old: " + keepsOriginalAfterDuplicate(new OldStore()));
        System.out.println("fixed: " + keepsOriginalAfterDuplicate(new FixedStore()));
    }

    static boolean keepsOriginalAfterDuplicate(Store store) {
        return false; // Write the regression test here.
    }
}

interface Store {
    void add(String id, String title);
    String find(String id);
}

// The version from the bug report: it checks for a duplicate too late.
final class OldStore implements Store {
    private final Map<String, String> entries = new HashMap<>();

    public void add(String id, String title) {
        String previous = entries.put(id, title);
        if (previous != null) {
            throw new IllegalArgumentException("duplicate id");
        }
    }

    public String find(String id) {
        return entries.get(id);
    }
}

// The fixed version: the guard runs before put.
final class FixedStore implements Store {
    private final Map<String, String> entries = new HashMap<>();

    public void add(String id, String title) {
        if (entries.containsKey(id)) {
            throw new IllegalArgumentException("duplicate id");
        }
        entries.put(id, title);
    }

    public String find(String id) {
        return entries.get(id);
    }
}
Hint 1: the idea

Both versions throw on the duplicate, so a test that only checks "an exception happened" passes on both and protects nothing. The bug is in the state the store is left in, so the test has to read the store after the rejection.

Hint 2: a first step

Write the test against the buggy store first: add one entry, then add a duplicate inside a try that expects the rejection. Before returning anything, print what the store holds for that ID. The printed value tells you what the test must compare.

Show one solution
Java
import java.util.Map;
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        System.out.println("old: " + keepsOriginalAfterDuplicate(new OldStore()));
        System.out.println("fixed: " + keepsOriginalAfterDuplicate(new FixedStore()));
    }

    static boolean keepsOriginalAfterDuplicate(Store store) {
        store.add("A1", "Read");
        try {
            store.add("A1", "Lost");
            return false; // A duplicate must be rejected.
        } catch (IllegalArgumentException expected) {
            // The rejection is required, but it is not the whole contract.
        }
        return "Read".equals(store.find("A1"));
    }
}

interface Store {
    void add(String id, String title);
    String find(String id);
}

// The version from the bug report: it checks for a duplicate too late.
final class OldStore implements Store {
    private final Map<String, String> entries = new HashMap<>();

    public void add(String id, String title) {
        String previous = entries.put(id, title);
        if (previous != null) {
            throw new IllegalArgumentException("duplicate id");
        }
    }

    public String find(String id) {
        return entries.get(id);
    }
}

// The fixed version: the guard runs before put.
final class FixedStore implements Store {
    private final Map<String, String> entries = new HashMap<>();

    public void add(String id, String title) {
        if (entries.containsKey(id)) {
            throw new IllegalArgumentException("duplicate id");
        }
        entries.put(id, title);
    }

    public String find(String id) {
        return entries.get(id);
    }
}

Expected output:

Text
old: false
fixed: true

The deciding line is the last one: find("A1") after the rejection. OldStore throws too, but only after put has already replaced Read with Lost, so the test returns false for it. A test that stopped at the catch would print true for both versions, and the bug could come back unnoticed. In a real suite you would keep only the FixedStore call, wrapped in check(...).

Change it and test again

Delete the return false; inside the try of keepsOriginalAfterDuplicate, then write a third Store that silently ignores duplicates without throwing. Does your test notice? Decide whether "a duplicate must be rejected" belongs in this regression test or in a separate one, and write down the defect each test is meant to catch. A large number of checks is less useful than checks that challenge different decisions.

Explain before moving on

What evidence does a passing mutation check add? Why should rejection tests inspect state after the failed operation, especially for repositories?

Was this article helpful?

Your response is saved on this device.