Using stubs for pre-canned results
The previous section explained that test doubles were a kind of object that could stand in for a production object so that we could write a test more easily. In this section, we will take a closer look at that test double and generalize it.
In the preceding DiceRoll
example, the test was simpler to write because we replaced the random number generation with a known, fixed value. Our genuine random number generator made it difficult to write an assertion, as we were never sure what the expected random number should be. Our test double was an object that instead supplied a well-known value. We can then work out the expected value for our assertion, making our test easy to write.
A test double that supplies values like this is called a stub. Stubs always replace an object that we cannot control with a test-only version that we can control. They always produce known data values for our code under test to consume. Graphically, a stub looks like this...