Test Doubles – Stubs and Mocks
In this chapter, we’re going to solve a common testing challenge. How do you test an object that depends on another object? What do we do if that collaborator is difficult to set up with test data? Several techniques are available to help us with this and they build on the SOLID principles we learned previously. We can use the idea of dependency injection to enable us to replace collaborating objects with ones specially written to help us write our test.
These new objects are called test doubles, and we will learn about two important kinds of test double in this chapter. We will learn when to apply each kind of test double and then learn two ways of creating them in Java – both by writing the code ourselves and by using the popular library Mockito. By the end of the chapter, we will have techniques that allow us to write tests for objects where it is difficult or impossible to test them with the real collaborating objects in place...