In our journey through isolating dependencies with test doubles, we've explored dummies, stubs, and spies. This lesson focuses on mocks, which are powerful test doubles capable of simulating external dependencies in software tests. You may have noticed in the previous unit how spying on the real implementation can be messy. Mocks can imitate the behavior of complex systems, allowing us to test code in isolation without relying on real and sometimes unpredictable systems like databases or web services.
Now, let's review the TDD workflow:
- Red: Write a failing test.
- Green: Write the minimum code to pass the test.
- Refactor: Improve the code structure without changing its behavior.
We'll demonstrate these principles using mocks, helping you to effectively isolate and test your application logic.
Mocks are indispensable in TDD because they allow you to test your code independently of the parts of the system you don't control. For instance, when writing tests for a PricingService
, you don't want tests to fail because an external currency conversion API goes down or changes unexpectedly. Mocks provide a controlled environment where you can simulate various conditions and responses as well as validate the calls.
Mocks, unlike spies, fully simulate the dependencies rather than simply observing their behavior. A mock creates a controlled substitute for a dependency, so the actual code or functionality isn’t executed. For instance, if a function interacts with an external API, a mock can simulate different responses from that API without making a network request.
Let's dive into mocking with Moq. We'll start with the basics: how to mock a class and its methods.
Consider the ExchangeRateService
, which fetches exchange rates from an API. In testing the PricingService
, we need to mock this service to ensure our tests don't rely on actual API responses.
Here's a simple way to mock with Moq:
C#1using Moq; 2using Xunit; 3 4public class PricingServiceTest 5{ 6 private readonly Mock<IExchangeRateService> _mockExchangeRateService; 7 private readonly PricingService _pricingService; 8 9 public PricingServiceTest() 10 { 11 _mockExchangeRateService = new Mock<IExchangeRateService>(); 12 _pricingService = new PricingService(_mockExchangeRateService.Object); 13 } 14 15 [Fact] 16 public async void ConvertPrice_ShouldUseExchangeRate() 17 { 18 // Arrange 19 _mockExchangeRateService.Setup(service => service.GetRate("USD", "EUR")) 20 .ReturnsAsync(1.5); 21 22 // Act 23 var result = await _pricingService.ConvertPrice(100, "USD", "EUR"); 24 25 // Assert 26 _mockExchangeRateService.Verify(service => service.GetRate("USD", "EUR"), Times.Once); 27 Assert.Equal(150.00, result); 28 } 29}
In this setup:
- We use
Moq
to mock theIExchangeRateService
. This mock object allows control over returned values and behavior without implementing the actual logic. _mockExchangeRateService.Setup()
is used to simulate a method that returns a predefined value when called.
Typing _mockExchangeRateService
as Mock<IExchangeRateService>
ensures Moq recognizes it as a mock and includes methods like Setup
and Verify
.
Next, we write the necessary code in the PricingService
to pass the test:
C#1public interface IExchangeRateService 2{ 3 Task<double> GetRate(string fromCurrency, string toCurrency); 4} 5 6public class PricingService 7{ 8 private readonly IExchangeRateService _exchangeRateService; 9 10 public PricingService(IExchangeRateService exchangeRateService) 11 { 12 _exchangeRateService = exchangeRateService; 13 } 14 15 public async Task<double> ConvertPrice(double amount, string fromCurrency, string toCurrency) 16 { 17 var rate = await _exchangeRateService.GetRate(fromCurrency, toCurrency); 18 return Math.Round(amount * rate, 2); 19 } 20}
When the test runs, it should pass, as we've implemented just enough logic to meet the test's expectations.
Mocks aren't limited to simple returns; they can simulate complex interactions, handle exceptions, or even return different values based on input:
C#1_mockExchangeRateService.Setup(service => service.GetRate(It.IsAny<string>(), It.IsAny<string>())) 2 .ReturnsAsync((string from, string to) => 3 { 4 if (from == "USD" && to == "EUR") return 0.85; 5 if (from == "USD" && to == "GBP") return 0.73; 6 return 1.0; 7 });
This flexibility allows for comprehensive testing of edge cases and alternative paths, ensuring your application handles real-world scenarios robustly.
In this lesson, we explored the power of mocks within the TDD framework, using C#, xUnit, and Moq. By isolating dependencies using mocks, we can ensure our tests are reliable and focused on our application's logic:
- Red: Begin with a failing test to clarify the functionality you're developing.
- Green: Implement the minimum necessary code using mocks to pass the test.
- Refactor: Clean and refine code without changing its behavior.
You're now ready to enter the practice exercises, where you'll apply these concepts to further solidify your understanding. By mastering these skills, you're well on your way to creating more robust and scalable applications. Keep practicing, and congratulations on reaching this point in the course!