Skip to the guide

Designing for testability

IntermediateConcept6 pages

A class is easy to test when a test can control everything it depends on and check everything it does. The hard parts are the things that change on their own between runs: the time, IDs, random numbers and outside services. Interviewers want to hear how you would test your design, and that you shaped the classes so the answer is simple.

A flight simulator

Think of how pilots practise a landing at night in a storm. Nobody waits for a real storm at midnight. They sit in a flight simulator, where the cockpit is the same as in the real aircraft. The only difference is the sky outside the windows, which an instructor controls from her panel. She can set dusk, add wind, or jump forward an hour, and the pilot sees it at once.

The simulated sky is not the real one, but it behaves like it, and it does exactly what the instructor sets. She can also check from her panel that the pilot called the control tower at the right moment.

In code, this page's project is a flashcard deck for learning words, where a card answered right comes back after 1 day, then 2, then 4. The cockpit is the Deck, which runs the same code in a test as in the app. The real sky is the system clock. The instructor's panel is the deck's constructor, which takes a Clock, and the simulated sky is FixedClock, a clock the test sets and moves forward. Checking the call to the tower is what a mock does, as you'll see below.