Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Find the hidden inputs (20 minutes)
List every hidden input and output in a method that reads LocalDate.now(), queries a database and prints a receipt.
Done when: at least three are listed with the seam that would replace each.
Hint
The clock, the database and the printer each need a seam.
Easy 2: Run the booking tests (20 minutes)
Type BookingService and the three stand-ins. Run the five checks with a small check method.
Done when: all five pass.
Hint
FakeClock has a field you can set.
Easy 3: Name the tests (20 minutes)
Write five test names, in plain words, for a Wallet.withdraw method.
Done when: each name says a situation and the expected result.
Hint
Use "when ... then ..." in the name.
Medium
Medium 1: Break and repair (45 minutes)
Change BookingService to call Instant.now() directly. Try to write the "same slot becomes past" test. Then repair the design.
Done when: you show why the first version cannot be tested, and the second can.
Hint
The test cannot move Instant.now().
Medium 2: Failing store (45 minutes)
Write a FailingStore whose save throws. Test that a failure sends no message.
Done when: the test passes after you order the calls so that save comes before send.
Hint
Save first, then send.
Medium 3: Parking fee tests (45 minutes)
For the fee strategies of Level 4, module 1, write tests for the hourly and the free-first-hour rule, with edge cases at 0, 60 and 61 minutes.
Done when: six tests pass and each has a clear name.
Hint
Boundaries are where mistakes hide.
Hard
Hard 1: Test a notification retry (90 minutes)
A service retries a failed send up to three times. Design the seam, write a notifier that fails twice and then works, and test the retries.
Done when: tests show success on the third try, and failure and no more calls after the fourth.
Hint
The fake counts calls and throws on the first two.
Hard 2: Make a legacy class testable (90 minutes)
Take a class that creates its own FileWriter, reads System.currentTimeMillis() and calls a static helper. Add seams without changing behaviour, and write tests.
Done when: the class takes three injected collaborators and has at least four passing tests.
Hint
Extract an interface for each hidden dependency.
Hard 3: Test pyramid plan (90 minutes)
For the booking system, plan which tests are unit tests with fakes, which use a real in-memory database, and which run the full flow. Say how many of each and why.
Done when: a table lists layers, counts (made up), speed and what each layer can catch.
Hint
More fast unit tests, fewer slow full-flow tests.