Using Stubs for Controlled Testing
Explore the role of stubs as test doubles to replace uncontrollable objects with controlled test-specific versions. Understand how stubs enable predictable unit tests by providing known data values to the System Under Test. Learn when to use stubs such as for databases, time-dependent code, or third-party services, and why stubs are not suitable for testing push-model interactions.
The previous lesson 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 lesson, we’ll take a closer look at that test double and generalize it.
Stubs for testing simplification
In the previous 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 ...