CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 2 min read

Hard to test

Hidden inputs and hidden outputs.

Think of testing a car's brakes. On a test track, the tester controls the speed, the road and the weather. On a public road, those vary every time. A test that depends on things the tester cannot control proves little, and the result may differ on every run.

Code is hard to test for the same reason. It reads inputs that a test cannot set, or produces effects that a test cannot see. Typical culprits:

  • The system clock. A method that calls Instant.now() gives a different answer each time, and a test of "bookings must start in the future" works today and fails tomorrow.
  • A real database, file or network. These are slow, may be unavailable, and keep state between tests.
  • Messages sent to the outside world. A real email goes to a real person.
  • Static calls and singletons. A call to a static method cannot be replaced (Level 3, module 4).
  • Objects created inside the method with new. The test cannot swap them.

CC calls the fix a matter of design. It suggests isolating code from the operating system, and replacing the timing calls with ones the test controls, so that a test can step time forward and watch the result. CA describes the same idea as a seam: a point where one part can be replaced without editing the code around it. A seam is an interface that the code depends on, with the real thing behind it in production and a stand-in in tests. This is the dependency inversion principle of Level 2, module 5.

Seam

A seam is a place in the code where one implementation can be swapped for another, so a test can replace the real thing.

Example: a Clock interface, with the real clock in production and a fixed clock in a test.

Check yourself: 1. Why is a method that calls Instant.now() hard to test? 2. Name three hidden inputs or outputs. 3. What is a seam?