Increasing Testability - Adding Interfaces and Mocks
Introduction
Welcome to the third lesson of the Increasing Code Test Coverage course! In our previous lessons, we explored the importance of code test coverage and how characterization tests can help document existing behavior. Now, we will focus on increasing testability by using traits and mocks.
This lesson will guide you through the process of decoupling dependencies, which is crucial for writing effective and reliable tests. By the end of this lesson, you'll understand how to refactor code to make it more testable and how to use Mockito's mocking capabilities to create mock objects for testing.
Understanding the Problem
Testing code with tightly coupled dependencies can be challenging. When a class directly depends on external services, such as email or database services, it becomes difficult to isolate the code under test. This can lead to unreliable and non-repeatable tests. For instance, if our OrderProcessor class directly calls an EmailService to send confirmation emails, testing the OrderProcessor without actually sending emails becomes problematic. The goal is to isolate the code under test to ensure that our tests are reliable and repeatable, while not triggering side effects and not depending on logic that isn't being tested directly.
Introducing Traits
Traits play a crucial role in decoupling dependencies. By defining a trait, you create a contract that different implementations can adhere to. This allows you to substitute real implementations with test doubles, such as mocks or stubs, during testing. For example, instead of directly using an EmailService in our OrderProcessor, we can define an EmailService trait. This trait can then be implemented by the EmailService class.
Here's the EmailService in question:
This class can be adjusted to adhere to a trait that defines the contract for the relevant class:
By using the EmailService trait, we can easily swap out the real EmailService with a mock during testing, allowing us to test the OrderProcessor without sending actual emails.
