Welcome to the second lesson in our exploration of Test-Driven Development (TDD) using C#, xUnit, and Moq. In the previous lesson, we covered how to utilize dummies to isolate dependencies. In this lesson, our focus will shift to another type of test double — Stubs.
By the end of this lesson, you will understand what stubs are and how to implement them in your tests, specifically for isolating dependencies like external services within the C# ecosystem.
In testing, test doubles help us isolate parts of our application. We've previously discussed dummies. Now, we will explore stubs, a more useful type of test double. Stubs provide predefined answers to method calls during testing. Unlike other test doubles, stubs do not track their usage, making them simpler yet powerful for certain scenarios.
Stubs are particularly useful when testing functions that rely on external services or complex dependencies. By simulating function outputs, stubs make tests faster and more predictable. Keep in mind that stubs focus on ensuring your application's logic functions as expected without verifying the correctness of external dependencies.
In C#, Moq
is a popular library used to create stubs. It allows us to set up return values that simulate how dependencies should behave in a controlled environment. This predictability isolates and tests your application's logic without relying on the behavior of external systems, which might be complex or introduce variability.
To illustrate the concept of stubs, we will create a WeatherAlertService
using stubs in a test-driven development process.
We will build a WeatherAlertService
that fetches data from a WeatherService
. This service will issue alerts based on specific conditions. The external data source is impractical for testing, so we'll use stubbed data for our tests instead.
Create a new test class named WeatherAlertServiceTests.cs
with the following test setup:
C#1using Xunit; 2 3class WeatherServiceStub : IWeatherService 4{ 5 private int _temperature = 20; 6 private string _conditions = "sunny"; 7 8 public void SetWeather(int temperature, string conditions) 9 { 10 _temperature = temperature; 11 _conditions = conditions; 12 } 13 14 public Task<WeatherData> GetCurrentWeather(string location) 15 { 16 return Task.FromResult(new WeatherData 17 { 18 Temperature = _temperature, 19 Conditions = _conditions 20 }); 21 } 22} 23 24public class WeatherAlertServiceTests 25{ 26 private WeatherServiceStub weatherService; 27 private WeatherAlertService alertService; 28 29 public WeatherAlertServiceTests() 30 { 31 weatherService = new WeatherServiceStub(); 32 alertService = new WeatherAlertService(weatherService); 33 } 34 35 [Fact] 36 public async Task ShouldReturnHeatWarningWhenTemperatureIsAbove35() 37 { 38 // Arrange 39 weatherService.SetWeather(36, "sunny"); 40 41 // Act 42 var alert = await alertService.ShouldSendAlert("London"); 43 44 // Assert 45 Assert.Equal("Extreme heat warning. Stay hydrated!", alert); 46 } 47}
In this test:
- We create a hand-crafted stub
WeatherServiceStub
that implements theIWeatherService
interface. This stub allows us to customize the weather data by setting predefined values forTemperature
andConditions
via theSetWeather
method. - The stub’s
GetCurrentWeather
method returns aWeatherData
object with these predefined values, simulating expected weather conditions for the test scenario without usingMoq
. - The
xUnit
test validates whether theWeatherAlertService
correctly interprets the weather data and returns the appropriate alert, specifically checking if it generates a heat warning when the temperature exceeds 35 degrees.
Run this test, and expect it to fail initially, as WeatherAlertService
is not yet implemented to handle the specified conditions.
Implement the WeatherAlertService
class with minimal logic:
Create WeatherAlertService.cs
in your src
directory:
C#1using System.Threading.Tasks; 2 3public interface IWeatherService 4{ 5 Task<WeatherData> GetCurrentWeather(string location); 6} 7 8public class WeatherData 9{ 10 public int Temperature { get; set; } 11 public string Conditions { get; set; } 12} 13 14public class WeatherAlertService 15{ 16 private readonly IWeatherService weatherService; 17 18 public WeatherAlertService(IWeatherService weatherService) 19 { 20 this.weatherService = weatherService; 21 } 22 23 public async Task<string> ShouldSendAlert(string location) 24 { 25 var weather = await this.weatherService.GetCurrentWeather(location); 26 27 if (weather.Temperature > 35) 28 { 29 return "Extreme heat warning. Stay hydrated!"; 30 } 31 32 return null; 33 } 34}
Run the tests again. The objective is to pass the specific test scenario by implementing only the necessary logic without overengineering other cases.
In the initial implementation, we created a manual stub, WeatherServiceStub
, to simulate weather data. Now, we will refactor this by leveraging the Moq library to streamline the process and improve maintainability. Using Moq, we can create flexible and reusable stubs with minimal code.
The Moq library allows us to set up method expectations and return values dynamically. By substituting our hand-crafted stub with a Moq-based one, we achieve the same test outcomes but with enhanced clarity and simplicity. This approach decreases the potential for bugs and makes adjusting test parameters easier.
Here's how we refactor our WeatherAlertServiceTests
:
- Replace the
WeatherServiceStub
with aMock<IWeatherService>
. - Use the
Setup
method in Moq to define the expected inputs and outputs for theGetCurrentWeather
method. - Through Moq, we eliminate the need to manage state explicitly within our custom stub class.
The refactored test class using the Moq library is shown below:
C#1using Xunit; 2using Moq; 3using System.Threading.Tasks; 4 5public class WeatherAlertServiceTests 6{ 7 private Mock<IWeatherService> weatherServiceMock; 8 private WeatherAlertService alertService; 9 10 public WeatherAlertServiceTests() 11 { 12 weatherServiceMock = new Mock<IWeatherService>(); 13 alertService = new WeatherAlertService(weatherServiceMock.Object); 14 } 15 16 [Fact] 17 public async Task ShouldReturnHeatWarningWhenTemperatureIsAbove35() 18 { 19 // Arrange 20 weatherServiceMock 21 .Setup(ws => ws.GetCurrentWeather("London")) 22 .ReturnsAsync(new WeatherData { 23 Temperature = 36, 24 Conditions = "sunny", 25 }); 26 27 // Act 28 var alert = await alertService.ShouldSendAlert("London"); 29 30 // Assert 31 Assert.Equal("Extreme heat warning. Stay hydrated!", alert); 32 } 33}
This transition towards using Moq simplifies test management and focuses the tests more on behavior rather than setup intricacies.
In this lesson, we delved into the concept of stubs and how they serve as a practical method to isolate dependencies in tests. Here are the key takeaways:
- Stubs offer a way to replace external dependencies by providing predefined return values, facilitating the testing of functionalities reliant on services beyond our immediate control.
- Through the Red-Green-Refactor cycle, we emphasized writing tests that initially fail, implementing just enough logic to pass the tests, and refining the code consistently.
Prepare to apply these techniques in forthcoming exercises, where you’ll explore different scenarios utilizing stubs. This will enhance your skills in employing test doubles and adhering to the TDD methodology, ultimately advancing your ability to create dependable, thoroughly-tested code.