Mastering Test Challenges with Test Doubles and SOLID Principles

Explore the technique of employing test doubles to overcome testing complexities, such as unpredictable behaviors or error handling, in collaboration with the SOLID principles.

In this lesson, we’re going to learn techniques that allow us to test these challenging collaborations. We will introduce the idea of test doubles. We will learn how to apply the SOLID principles to design code flexible enough to use these test doubles.

Applying test doubles

The challenges of the previous section are solved by using test doubles. A test double replaces one of the collaborating objects in our test. By design, this test double avoids the difficulties of the replaced object. Think of them as the stunt doubles in movies, replacing the real actors to help safely get an action shot. A software test double is an object we have written specifically to be easy to use in our unit test. In the test, we inject our test double into the SUT in the Arrange step. In production code, we inject in the production object that our test double had replaced. Let’s reconsider our DiceRoll example earlier. How would we refactor that code to make it easier to test?

Creating an interface

Create an interface that abstracts the source of random numbers:

Get hands-on with 1200+ tech skills courses.