CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 4 of 6 · 2 min read

The tests

Short, independent, one idea each.

With the stand-ins, the tests are short. A fixed noon time (made up) sets the scene, and each test checks one idea.

@Test void booksAFutureSlot() {
    assertEquals("ok", service.book("b1", "asha", noon.plusSeconds(3600)));
    assertEquals(List.of("asha:booked b1"), notifier.sent);
}

@Test void duplicateSendsNothing() {
    service.book("b1", "asha", noon.plusSeconds(3600));
    assertEquals("duplicate", service.book("b1", "asha", noon.plusSeconds(3600)));
    assertEquals(1, notifier.sent.size());
}

@Test void pastStartIsRejectedAndNotSaved() {
    assertThrows(IllegalArgumentException.class,
        () -> service.book("b2", "x", noon.minusSeconds(1)));
    assertFalse(store.exists("b2"));
}

@Test void sameSlotBecomesPastAfterTimePasses() {
    clock.advance(Duration.ofHours(2));
    assertThrows(IllegalArgumentException.class,
        () -> service.book("b3", "x", noon.plusSeconds(3600)));
}

The five checks, run with a small hand-made check function, all pass. The last test is only possible because the clock is a seam. A real clock would need the test to wait two hours.

Notice how each test follows the same three steps: set up the state, perform one action, check the result. This is often written as given, when, then. CC advises one concept per test, and tests that read like a short description of behaviour. Test names say what should happen, such as pastStartIsRejectedAndNotSaved, so a failure explains itself.

Notice also that the third test checks the failure path from module 1: the booking is rejected and nothing is saved. That is failure atomicity under test. Always test the failure paths, since many bugs live there.

CC lists five rules for clean tests, summed up as F.I.R.S.T.

  • Fast. Slow tests are run less often, so problems are found late.
  • Independent. No test depends on another, and they can run in any order.
  • Repeatable. The result is the same on any machine, with no network.
  • Self-validating. A test passes or fails with no log to read.
  • Timely. Tests are written just before the code they check.

The injected seams give two of these directly. The fake clock and store make tests fast and repeatable.

Fake

A fake is a simple stand-in for a real dependency that works well enough for tests, and often keeps its data in memory.

Example: MemStore, which keeps bookings in a map.

Check yourself: 1. Why can the last test finish at once? 2. What three steps does each test follow? 3. What does F.I.R.S.T. stand for?