Welcome to our third lesson on Test-Driven Development (TDD) with Test Doubles. In this lesson, we focus on Spies, an essential test double type used to observe interactions with your code's dependencies during testing. By now, you've already been introduced to Dummies and Stubs in previous lessons, allowing you to manage dependencies via test doubles effectively.
Our goal here is to seamlessly integrate Spies into the TDD Red-Green-Refactor cycle: writing tests (Red), creating a minimal implementation (Green), and refactoring for better quality without altering behavior. Let's dive into understanding and using Spies within this framework!
Spies in Mockito allow you to observe and record how functions in your application are used without modifying their behavior. In TDD, Spies help verify that functions are called when and how you expect them to be, which is a vital part of writing reliable tests.
Spies can check:
- If a method was called
- How many times it was called
- With what arguments it was called
Spies align perfectly with the Red-Green-Refactor cycle!
Let's move on to setting up our environment, utilizing the powerful features of Mockito.
Let's consider a Notification Service example where we aim to ensure notifications are sent with appropriate priorities. We will begin by implementing a Spy on the send method of the RealNotificationSender using Mockito. This allows you to use an actual dependency within your test but verify how it was called.
Here's an example test file: NotificationServiceSpec.scala.
Here's the key parts of the above code:
- We create an actual instance of the
RealNotificationSender. - We create a Spy object of
RealNotificationSenderusingMockito.spy, which represents our Spy. - This Spy will help us verify interactions with the
sendmethod.
Next, we insert failing tests to see our Spies in action. Remember that writing failing tests is our "Red" step in TDD.
