Skip to lesson

Writing tests before the solution

Writing tests after you finish coding feels like a chore, and it tempts you to write weak tests that merely echo your code. Writing tests before the solution turns testing into a design tool that clarifies the method signature, locks in edge cases, and lets you optimise code without fear.

The test-first mindset: design the contract before the loop

Test-first means writing the test calls before the algorithm, which forces you to decide the method signature and edge-case behaviour up front. The code below is a stub maxProfit whose two tests fail first.

StubFirst.javaJava
public class StubFirst {    static int maxProfit(int[] prices) {        return -1; // stub: compiles, so the tests can run and fail    }
    static void check(int[] prices, int expected) {        int actual = maxProfit(prices);        System.out.println((actual == expected ? "PASS" : "FAIL") + ": expected " + expected + ", got " + actual);    }
    public static void main(String[] args) {        check(new int[] {7, 1, 5, 3, 6, 4}, 5);        check(new int[] {7, 6, 4, 3, 1}, 0);    }}
Output
FAIL: expected 5, got -1
FAIL: expected 0, got -1

Seeing a test fail on the stub proves that the test is actually running and checking the result rather than passing by accident.

Test-first means writing the check(...) or @Test calls before writing the algorithm. It forces you to answer three design questions up front:

  1. What is the exact method signature? What parameter types go in, and does it return int, long (to avoid overflow), int[], or boolean?
  2. How should edge cases behave? What should happen on an empty array, a negative number, or a missing target (-1, 0, or IllegalArgumentException)?
  3. How do I verify the test itself works? You start with a stub method (a placeholder body like return -1; or return 0;) and watch your new tests fail.
  • Stub method: A minimal compilable method body (such as return 0;) written so tests can compile and fail first.
  • Contract first: Writing callers first makes awkward parameter lists or return types obvious before you invest time in the body.
  • No confirmation bias: Expected outputs are locked in before any loop logic exists.

Red, Green, Refactor: the three-beat rhythm

Red, Green, Refactor is a three-step loop: see the tests fail, make them pass simply, then speed the code up. The code below follows it on Max Profit.

In DSA, this rhythm shines when moving from brute force to optimal: your brute-force implementation gets you to Green, and your test suite acts as a safety net while you Refactor to two pointers, sliding window, or hashing.

Example 1 · Brute force: Green stage, nested loops (O(n²) time, O(1) space)

GreenBruteDemo.javaJava
public class GreenBruteDemo {    // GREEN: the simple O(n^2) version that passes every test in the table    static int maxProfitGreenBrute(int[] prices) {        int best = 0;        for (int buy = 0; buy < prices.length; buy++) {            for (int sell = buy + 1; sell < prices.length; sell++) {                best = Math.max(best, prices[sell] - prices[buy]);            }        }        return best;    }
    public static void main(String[] args) {        int[][] inputs = {            {7, 1, 5, 3, 6, 4}, // Normal: buy at 1, sell at 6 -> 5            {7, 6, 4, 3, 1},    // Edge: strictly falling prices -> 0            {5},                // Edge: single day -> 0            {}                  // Edge: empty array -> 0        };        int[] expected = {5, 0, 0, 0};        int passed = 0;        for (int i = 0; i < inputs.length; i++) {            if (maxProfitGreenBrute(inputs[i]) == expected[i]) passed++;        }        System.out.println("GREEN stage (O(n^2) brute): " + passed + "/4 passed");    }}
Output
GREEN stage (O(n^2) brute): 4/4 passed

What this code does

  • The 4-case test table is written first. Against a stub that returns -1 it would score 0/4 (Red).
  • The obvious loop that tries every buy day and every later sell day reaches 4/4 (Green). It is slow, but correct, and now the tests guard it.

Example 2 · Optimal: Refactor stage, one pass (O(n) time, O(1) space)

RefactorOptimalDemo.javaJava
public class RefactorOptimalDemo {    // REFACTOR: the O(n) single pass, checked by the exact same test table    static int maxProfitRefactoredOptimal(int[] prices) {        int minPriceSoFar = Integer.MAX_VALUE;        int bestProfit = 0;        for (int price : prices) {            minPriceSoFar = Math.min(minPriceSoFar, price);            bestProfit = Math.max(bestProfit, price - minPriceSoFar);        }        return bestProfit;    }
    public static void main(String[] args) {        int[][] inputs = {            {7, 1, 5, 3, 6, 4}, // Normal: buy at 1, sell at 6 -> 5            {7, 6, 4, 3, 1},    // Edge: strictly falling prices -> 0            {5},                // Edge: single day -> 0            {}                  // Edge: empty array -> 0        };        int[] expected = {5, 0, 0, 0};        int passed = 0;        for (int i = 0; i < inputs.length; i++) {            if (maxProfitRefactoredOptimal(inputs[i]) == expected[i]) passed++;        }        System.out.println("REFACTOR stage (O(n) optimal): " + passed + "/4 passed");    }}
Output
REFACTOR stage (O(n) optimal): 4/4 passed

What this code does

  • The same four tests pass again, so the faster code is safe.
  • It is faster because the best day to buy before today is simply the lowest price seen so far, so one running minimum replaces the inner loop.

Test-Driven Development (TDD) follows a short, repeatable three-step cycle known as Red → Green → Refactor:

  • Red (Write a failing test): Write a stub method and your test table (normal, boundary, edge), run the tests, and confirm they fail (red).
  • Green (Make it pass simply): Write the simplest correct code — even a straightforward brute-force loop — until every test in your table passes (green).
  • Refactor (Improve speed or clarity safely): Replace the slow brute-force body with your fast O(n) algorithm or clean up messy variables, re-running the exact same tests after every edit to confirm everything stays green.
  1. Red: Create the method stub (return 0;), write your test cases, and verify they fail.
  2. Green: Write a clear, simple solution that passes every test case.
  3. Refactor: Optimise time/space complexity or clean up code structure while keeping all tests green.

Order of execution

Red, Green, Refactor

Tap the steps of one test-first cycle, in the order they happen.

Regression tests: stopping old bugs from ever returning

A regression is an old case that breaks after a code change, and a regression test is a permanent test that stops it returning. The code below shows both.

On real engineering teams, every bug ticket follows one rule: reproduce the bug with a failing test first, then fix the code until the test passes, and commit both together. That way, six months later when another developer refactors the class, the CI pipeline runs that regression test automatically.

Bad refactor: two pointers with left <= right

Step 1 of 4

Array: 3, 7, 11. left at index 0. right at index 2.
target
6
The sorted array has one 3. No two different elements add up to 6, so the correct answer is false.

Example 3 · Catching a regression introduced during optimization

RegressionNetDemo.javaJava
import java.util.Arrays;
public class RegressionNetDemo {    // Original Green O(n^2) solution: checks if any two DISTINCT indices sum to target    static boolean hasPairSumGreen(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j < nums.length; j++) {                if (nums[i] + nums[j] == target) return true;            }        }        return false;    }
    // Bad Refactor attempt: sorts and uses two pointers starting at (0, 0) instead of (0, n-1)    // Bug: left == right allows using the SAME element twice!    static boolean hasPairSumBadRefactor(int[] nums, int target) {        int[] copy = nums.clone();        Arrays.sort(copy);        int left = 0, right = copy.length - 1;        while (left <= right) { // Bug: '<=' instead of '<' reuses the middle element!            int sum = copy[left] + copy[right];            if (sum == target) return true;            if (sum < target) left++;            else right--;        }        return false;    }
    public static void main(String[] args) {        int[] input = {3, 7, 11}; // target = 6 (only one 3 exists!)        int target = 6;        System.out.println("Green reference on [3, 7, 11], target=6 : " + hasPairSumGreen(input, target));        System.out.println("Bad refactor on [3, 7, 11], target=6    : " + hasPairSumBadRefactor(input, target));    }}
Output
Green reference on [3, 7, 11], target=6 : false
Bad refactor on [3, 7, 11], target=6    : true

What this code does

  • While refactoring from O(n²) to two pointers, writing while (left <= right) instead of while (left < right) introduces a regression: when left == right, copy[0] + copy[0] = 3 + 3 = 6 reuses the same element.
  • Having the [3, 7, 11], target = 6 test case already in the suite catches the regression the moment you run the refactored method.

Example 4 · Adding a regression test when a bug is reported

BugTicketRegressionDemo.javaJava
public class BugTicketRegressionDemo {    // Formats cents as "$D.CC" (e.g., 1205 -> "$12.05", -5 -> "-$0.05")    static String formatCentsFixed(int totalCents) {        boolean neg = totalCents < 0;        long abs = Math.abs((long) totalCents);        long dollars = abs / 100;        long cents = abs % 100;        String core = "$" + dollars + "." + (cents < 10 ? "0" + cents : cents);        return neg ? "-" + core : core;    }
    static void assertEqualStr(String label, String expected, String actual) {        if (!expected.equals(actual)) {            throw new AssertionError(label + ": expected <" + expected + "> but was <" + actual + ">");        }        System.out.println("PASS: " + label + " -> " + actual);    }
    public static void main(String[] args) {        // Existing tests:        assertEqualStr("Whole dollars", "$5.00", formatCentsFixed(500));        assertEqualStr("Two-digit cents", "$12.34", formatCentsFixed(1234));        // Regression test #1: single-digit cents needs leading zero (1205 -> $12.05, not $12.5)        assertEqualStr("Regression: single-digit cents", "$12.05", formatCentsFixed(1205));        // Regression test #2: negative cents under $1 (-5 -> -$0.05, not $0.-5)        assertEqualStr("Regression: negative sub-dollar", "-$0.05", formatCentsFixed(-5));    }}
Output
PASS: Whole dollars -> $5.00
PASS: Two-digit cents -> $12.34
PASS: Regression: single-digit cents -> $12.05
PASS: Regression: negative sub-dollar -> -$0.05

What this code does

  • Single-digit cents (1205 → 12.05) and negative sub-dollar amounts (-5 → -0.05) are classic production bugs.
  • Keeping those two lines permanently in the test suite ensures no future cleanup accidentally breaks leading zeroes or negative signs.

A regression is when a previously working feature or edge case breaks after a code change (for example, while optimising an O(n²) method to O(n) or fixing a different bug). A regression test is a permanent test case added for a specific bug you discovered so that the bug can never sneak back in.

Whenever you find a failing input (by hand, from a stress test, or from a bug report), add it to your test list before editing your solution code.

Next step

Check your understanding

10 quick questions