8

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 ...

Get Test-Driven Development with Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.