What makes a test good: fast, isolated, readable
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A test that sometimes fails for no reason is worse than no test: people learn to ignore it, and a real bug slips through. ShopLite needs tests the team can trust, quick and repeatable, that say in one line what broke.
FIRST: fast, isolated, repeatable, self-checking, timely
FIRST is a checklist for good unit tests: Fast, Isolated, Repeatable, Self-checking and Timely. A test with all five properties can be trusted and run after every change.
The first test below only prints a number. The second knows the answer and decides by itself, the S in FIRST.
Example 1 · Not self-checking versus self-checking
public class SelfCheckingDemo { static int attendancePercent(int attended, int total) { return attended * 100 / total; }
// Bad: prints a number and hopes someone reads it static void printingTest() { System.out.println("attendance for 45 of 60: " + attendancePercent(45, 60)); }
// Good: compares with the expected value and decides by itself static void selfCheckingTest() { int expected = 75; int actual = attendancePercent(45, 60); if (actual != expected) { throw new AssertionError("expected " + expected + " but was " + actual); } System.out.println("PASS attendanceOf45OutOf60Is75Percent"); }
public static void main(String[] args) { printingTest(); selfCheckingTest(); }}attendance for 45 of 60: 75 PASS attendanceOf45OutOf60Is75Percent
What this code does
- The printing "test" never fails: if the method returned 74, it would print 74 and a busy reader would still see a number and move on.
- The self-checking version knows the answer (45 of 60 is 75%) and throws an
AssertionErrorwhen it differs, which is exactly how JUnit's assertions report a failure.
Each letter is one property of a good test:
- Fast: milliseconds, so you run all of them after every change.
- Isolated: no test depends on another test or on what another test left behind; any test can run alone or in any order.
- Repeatable: same result on every run, on every computer, at any time of day, with no network needed.
- Self-checking: the test decides PASS or FAIL itself; nobody reads printed values.
- Timely: written together with the code, not months later.
Predict the output
Which FIRST letter breaks?
Read each test and pick the property it breaks.
Round 1 of 4
Which property does this test break?
One behaviour per test, and a name that says it
A behaviour is one promise the code makes, such as "orders of Rs 499 or more have free delivery". A good test checks one behaviour, and its name states it as a sentence.
This runner has two bugs: delivery is charged at exactly Rs 499, and GST is 12% instead of 18%. See how one big test reports them, then small named tests.
Example 2 · One big test hides failures; small named tests show them
import java.util.LinkedHashMap;import java.util.Map;
public class OneBehaviourDemo { // Two bugs: delivery is charged at exactly Rs 499, and GST is 12% instead of 18% static int delivery(int subtotal) { return subtotal > 499 ? 0 : 40; }
static int gst(int amount) { return amount * 12 / 100; }
static void assertEquals(int expected, int actual) { if (expected != actual) throw new AssertionError("expected " + expected + " but was " + actual); }
static void run(Map<String, Runnable> tests) { for (Map.Entry<String, Runnable> t : tests.entrySet()) { try { t.getValue().run(); System.out.println(" PASS " + t.getKey()); } catch (AssertionError e) { System.out.println(" FAIL " + t.getKey() + ": " + e.getMessage()); } } }
public static void main(String[] args) { Map<String, Runnable> big = new LinkedHashMap<>(); big.put("testOrder", () -> { assertEquals(40, delivery(120)); assertEquals(0, delivery(499)); // fails here... assertEquals(18, gst(100)); // ...so this bug stays hidden }); System.out.println("One big test:"); run(big);
Map<String, Runnable> small = new LinkedHashMap<>(); small.put("ordersBelowRs499PayRs40", () -> assertEquals(40, delivery(120))); small.put("exactlyRs499HasFreeDelivery", () -> assertEquals(0, delivery(499))); small.put("gstIs18Percent", () -> assertEquals(18, gst(100))); System.out.println("Small named tests:"); run(small); }}One big test: FAIL testOrder: expected 0 but was 40 Small named tests: PASS ordersBelowRs499PayRs40 FAIL exactlyRs499HasFreeDelivery: expected 0 but was 40 FAIL gstIs18Percent: expected 18 but was 12
What this code does
- The big test stops at its first failed check, so the GST bug is not reported at all, and the name
testOrdersays nothing about which rule broke. - Split into one behaviour per test, the report lists both broken promises by name. You can read "exactly Rs 499 has free delivery: FAIL" and know the fix (
>=) before opening the code.
When a test checks five things, the first failure stops it and hides the other four, and its name cannot tell you which promise broke. Small, well-named tests turn a failure report into a list of broken promises you can read without opening the code.
Name tests as sentences: freeDeliveryFromRs499, not test1 or testCart.
Find the bug
Fix the weak test
Tap the line that makes each test hard to trust, then read the fix.
This test fails one day. Does its name help?
Round 1 of 3Flaky tests and their causes
A flaky test passes and fails on different runs without any change to the code. The cause is something the test does not control, such as the clock, random values, shared state or the network.
Two tests below share one static cart. Run in one order, both pass. Run in the other order, one fails.
Example 3 · Shared state: the result depends on test order
import java.util.ArrayList;import java.util.List;
public class TestOrderDemo { static List<String> cart = new ArrayList<>(); // shared by every test: the problem
static void assertEquals(int expected, int actual) { if (expected != actual) throw new AssertionError("expected " + expected + " but was " + actual); }
static void addingAnItemGivesOneItem() { cart.add("Notebook"); assertEquals(1, cart.size()); }
static void aNewCartIsEmpty() { assertEquals(0, cart.size()); }
static void runInOrder(String label, Runnable... tests) { cart.clear(); // a fresh start for this run only System.out.print(label + ":"); for (Runnable test : tests) { try { test.run(); System.out.print(" PASS"); } catch (AssertionError e) { System.out.print(" FAIL (" + e.getMessage() + ")"); } } System.out.println(); }
public static void main(String[] args) { runInOrder("empty test first", TestOrderDemo::aNewCartIsEmpty, TestOrderDemo::addingAnItemGivesOneItem); runInOrder("add test first ", TestOrderDemo::addingAnItemGivesOneItem, TestOrderDemo::aNewCartIsEmpty); }}empty test first: PASS PASS add test first : PASS FAIL (expected 0 but was 1)
What this code does
- Both tests use the same
staticcart. In the first order they pass; in the second, the item added by one test is still there when the other test checks for an empty cart. - The tests are not isolated. The fix is to give every test its own fresh cart (JUnit creates a new test object for every test method), never a shared
staticone.
The usual causes are things the test does not control:
- The clock:
LocalTime.now()inside the code, so an evening-sale test passes only between 4 and 6 pm. - Random values:
new Random()orUUID.randomUUID()without a fixed seed or a way to replace them. - Shared state and test order: a
staticlist or a database row changed by one test and read by another. - The network: a real payment gateway or website that is slow or down.
Order of execution
Hunt down a flaky test
Put the steps of fixing a flaky test in a sensible order.
Making time and randomness controllable
Clock.fixed creates a java.time.Clock stopped at one chosen moment. A class that asks a Clock for the time, instead of calling LocalTime.now(), can be tested at 16:30 on any day.
This pricing class gets a Clock in its constructor. The test hands it a stopped clock, so 16:30 is always 16:30.
Example 4 · A fixed Clock makes an evening-sale test repeatable
import java.time.Clock;import java.time.Instant;import java.time.LocalTime;import java.time.ZoneId;
class SalePricing { private final Clock clock;
SalePricing(Clock clock) { this.clock = clock; }
// 10% off between 16:00 and 18:00 int price(int listPrice) { LocalTime now = LocalTime.now(clock); boolean eveningSale = !now.isBefore(LocalTime.of(16, 0)) && now.isBefore(LocalTime.of(18, 0)); return eveningSale ? listPrice * 90 / 100 : listPrice; }}
public class FixedClockDemo { static Clock at(String isoInstant) { return Clock.fixed(Instant.parse(isoInstant), ZoneId.of("Asia/Kolkata")); }
public static void main(String[] args) { // 11:00 UTC is 16:30 in India; 13:00 UTC is 18:30 System.out.println("16:30 -> Rs " + new SalePricing(at("2026-10-16T11:00:00Z")).price(60)); System.out.println("18:30 -> Rs " + new SalePricing(at("2026-10-16T13:00:00Z")).price(60)); System.out.println("16:00 -> Rs " + new SalePricing(at("2026-10-16T10:30:00Z")).price(60));
SalePricing live = new SalePricing(Clock.systemDefaultZone()); System.out.println("Live pricing ready: " + (live.price(60) > 0)); }}16:30 -> Rs 54 18:30 -> Rs 60 16:00 -> Rs 54 Live pricing ready: true
What this code does
SalePricingnever callsLocalTime.now()on its own; it asks theClockit was given. A test passesClock.fixed(...), so 16:30 is 16:30 on every run, at any real time of day.- The checks at 16:30, 18:30 and exactly 16:00 would be impossible to repeat with the real clock. Only the application's start-up code uses
Clock.systemDefaultZone().
Example 5 · A seeded Random makes coupon codes repeatable
import java.util.Random;
class CouponCodes { private static final String LETTERS = "ABCDEFGHJKLMNPQRSTUVWXYZ"; // no I or O private final Random random;
CouponCodes(Random random) { this.random = random; }
String next() { StringBuilder code = new StringBuilder("FEST-"); for (int i = 0; i < 4; i++) { code.append(LETTERS.charAt(random.nextInt(LETTERS.length()))); } return code.toString(); }}
public class SeededRandomDemo { public static void main(String[] args) { CouponCodes first = new CouponCodes(new Random(42)); CouponCodes second = new CouponCodes(new Random(42));
String a = first.next() + " " + first.next(); String b = second.next() + " " + second.next(); System.out.println("Run 1: " + a); System.out.println("Run 2: " + b); System.out.println("Same codes: " + a.equals(b)); System.out.println("Format ok: " + a.matches("FEST-[A-Z]{4} FEST-[A-Z]{4}")); }}Run 1: FEST-CDAW FEST-UPTQ Run 2: FEST-CDAW FEST-UPTQ Same codes: true Format ok: true
What this code does
- Two
Randomobjects with the same seed (42) produce the same numbers, so the generated codes are identical on every run and on every computer. A test can rely on them. - When exact values do not matter, a test can also check a property that is always true, such as the format
FEST-plus four capital letters, which passes for any seed.
Randomness works the same way. A java.util.Random created with a seed (a starting number), such as new Random(42), produces the same numbers on every run. The application passes Clock.systemDefaultZone() and new Random(); the test passes fixed ones.
Trace the code
Same seed, same numbers
Variables
None yet.
Output
(nothing printed yet)Line 3a is a Random that starts from the seed 42.
Tests as documentation
Tests as documentation means a reader learns what the code promises from the test names and expected values. Unlike a comment, a test cannot go out of date silently: when the code changes, it fails.
Read only the test names below. You can already tell ShopLite's delivery rules without opening the code.
class DeliveryChargeTest {
@Test void ordersBelowRs499PayRs40Delivery() { ... }
@Test void anOrderOfExactlyRs499HasFreeDelivery() { ... }
@Test void largeOrdersHaveFreeDelivery() { ... }
@Test void aNegativeSubtotalIsRejected() { ... }}Write each test so it reads as a small example: the inputs, the action, the expected result, and a name that is a full sentence. A new team member should understand the delivery rules from the test class alone.
Next step
Check your understanding
11 quick questions