Using Stubs for Controlled Testing
Understand how stubs provide controlled test values, particularly for scenarios like database access, time-dependent behaviors, and interaction with third-party services.
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 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:
Get hands-on with 1200+ tech skills courses.