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’ll introduce the idea of test doubles. We’ll 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 lesson 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 test doubles 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’ve written specifically to be easy to use in our unit test. In the test, we inject our test double into the system under test (SUT) in the Arrange step. In the 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

First, we create an interface that abstracts the source of random numbers:

Get hands-on with 1200+ tech skills courses.