Lesson 3
Utilizing Spies in Test Driven Development with Moq
Introduction and Context Setting

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!

Deep Dive into Spies in Moq

Spies in Moq 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:

  • Red: Write a failing test to ensure your code's behavior is verified.
  • Green: Implement only enough code for the tests to pass.
  • Refactor: Clean up the tests and the implementation for better software design.

Let's move on to setting up our environment, utilizing the powerful features of Moq.

Example: Implementing the First Spy

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 Moq. This allows you to use an actual dependency within your test but verify how it was called.

Here's an example test file: NotificationServiceTests.cs.

C#
1using Moq; 2using Xunit; 3 4public class NotificationServiceTests 5{ 6 private Mock<RealNotificationSender> senderSpy; 7 private NotificationService notificationService; 8 9 public NotificationServiceTests() 10 { 11 // Arrange 12 senderSpy = new Mock<RealNotificationSender>() 13 { 14 CallBase = true 15 }; 16 17 notificationService = new NotificationService(senderSpy.Object); 18 } 19 20 21 // Test cases to follow... 22}
Explanation
  • We create an actual instance of the RealNotificationSender.
  • We create a Mock object of RealNotificationSender, which represents our Spy.
  • CallBase = true: This ensures that the real implementation of the methods in RealNotificationSender will be called unless they are explicitly set up with a different behavior. This is useful when you want to use the actual functionality of some methods but still track and verify the method calls.
  • This Spy will help us verify interactions with the Send method.

Next, we insert failing tests to see our Spies in action. Remember that writing failing tests is our "Red" step in TDD.

Example: Testing with Spies

Let's add some test cases to observe the behavior of the Send method using our Moq Spy.

C#
1[Fact] 2public async Task NotifyUser_ShouldSendNotificationWithLowPriorityForShortMessages() 3{ 4 // Act 5 await notificationService.NotifyUser("user1", "Hi!"); 6 7 // Assert 8 senderSpy.Verify(s => s.Send(It.IsAny<Notification>()), Times.Once); 9 10 senderSpy.Verify(s => s.Send(It.Is<Notification>(n => 11 n.UserId == "user1" && 12 n.Message == "Hi!" && 13 n.Priority == Priority.Low 14 )), Times.Once); 15}
Explanation
  • We create a failing test to ensure our notification sends with low priority.
  • The Moq Verify method captures and observes interactions of the Send method.
  • Times.Once verifies how often it was called, while It.IsAny<Notification> checks for any parameters as long as it receives a Notification.

Upon running this test, it will fail initially as we have not written the corresponding implementation. This is the Red step of our cycle. Implementing minimal logic in the NotificationService class will move us towards making the test pass (Green).

Understanding Moq's Verify functionality

Moq's Verify function is a powerful tool for asserting that specific interactions with mock objects occurred as expected during a test. It allows you to check whether a particular method was called on the mock object, how many times it was called, and with what parameters.

In the first example:

C#
1senderSpy.Verify(s => s.Send(It.IsAny<Notification>()), Times.Once);
  • s => s.Send(It.IsAny<Notification>()): This lambda expression specifies the method you're checking. It.IsAny<Notification>() is an It matcher that indicates any instance of Notification is acceptable.
  • Times.Once: This verifies that the Send method was called exactly one time.

In the second example:

C#
1senderSpy.Verify(s => s.Send(It.Is<Notification>(n => 2 n.UserId == "user1" && 3 n.Message == "Hi!" && 4 n.Priority == Priority.Low 5)), Times.Once);
  • It.Is<Notification>(n => ...): This is a more specific matcher. It uses a predicate to assert not just any Notification, but specifically one where UserId is "user1", Message is "Hi!", and Priority is Priority.Low.
  • The same Times.Once ensures the method is called exactly once with these specific argument conditions.

These assertions help ensure that the code behaves correctly by verifying interactions with each dependency, crucial in a test-driven development approach.

Making the Test Pass (Green)

After writing a failing test to capture how our Send method should behave, the next step is to implement the minimal functionality required to make the test pass. This involves modifying the NotificationService class to utilize the Send method correctly based on the specified logic.

Here's an example of updating the NotificationService to fulfill the test requirements:

C#
1public class NotificationService 2{ 3 private readonly INotificationSender _sender; 4 5 public NotificationService(INotificationSender sender) 6 { 7 _sender = sender; 8 } 9 10 public async Task NotifyUser(string userId, string message) 11 { 12 await _sender.Send(new Notification {}); 13 } 14}
Explanation
  • The Send method is invoked with the userId, message, and priority.
  • Since there is only one test, this is the minimal amount of code necessary to get the test to pass.

With this implementation, re-running the test should now pass, taking us from the Red to the Green phase of TDD.

Review, Summary, and Next Steps

In this lesson, we've explored the importance of Spies as test doubles in the TDD process using C#, xUnit, and Moq. Here's what we've achieved:

  • Red: Set up tests simulating real-world scenarios, initially leading them to fail.
  • Green: We strategized to write the least amount of functionality to fulfill all test criteria.
  • Refactor: Ensured our code and tests remain clean, scalable, and comprehensible.

As we transition into practice exercises, focus on implementing Spies in different scenarios to solidify these concepts. The exercises will guide you in writing, verifying, and refactoring tests with Spies, empowering you to integrate this knowledge into complex projects.

Happy testing and enjoy the lessons you've built through TDD in C# with xUnit and Moq!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.