Chapter 7. Test-driving the unpredictable
Horses are predictably unpredictable.
Loretta Gage, the oldest student at Colorado State University’s College of Veterinary Medicine
So far, we’ve dealt with data-access code, web components, and regular business logic. The common denominator for what we’ve seen so far is that this type of code executes somewhat detached from the underlying platform and, most notably, executes in a predictable manner. Not all code is like that. In this chapter, we’ll drop the gloves and go knuckle-to-knuckle against specific domains of programming in Java, which involve unpredictable functionality and are typically somewhat more complex to work with in a test-first manner:
- Time-dependent functionality
- Multithreaded programming
We’ll start from time-dependent functionality because it’s the least troublesome of the bunch, and then we’ll move on to discuss the kinds of problems multithreading and concurrent programming represent to testing and, thus, to test-driven development. To finish off the chapter, we’ll arm ourselves with knowledge of the basic synchronization objects provided by the java.util.concurrent package.
Many developers have at least once been faced with the problem of writing a test for a piece of code whose output or behavior depends on the current time. The problem with time is that we can’t control it. That is, unless we make it so. Let us concretize the problem and the solution with an example.