Isolating Dependencies with Test Doubles: Stubs
Introduction and Context Setting
Welcome to the second lesson in our journey into Test-Driven Development (TDD) using Go and Testify. In the previous lesson, we discussed how to utilize dummies to isolate dependencies. In this lesson, we will shift our focus to another kind of test double — Stubs.
By the end of this lesson, you'll understand what stubs are and how to implement them in your tests using Go, specifically for isolating dependencies like external services.
Understanding Stubs in Testing
In testing, test doubles help us isolate parts of our application. We've previously discussed dummies. Stubs, a more useful type of test double, provide predefined answers to method calls during testing. Unlike other test doubles, stubs aren't concerned with tracking usage; they are simple yet powerful for specific scenarios.
Stubs are especially useful when testing functions that rely on external services or complex dependencies. By simulating function outputs, stubs make tests faster and more predictable. Stubs focus on ensuring your application's logic functions as expected without verifying the correctness of external dependencies.
Example: Crafting a `WeatherAlertService` Using Stubs
To demonstrate the concept of stubs, we will create a WeatherAlertService using stubs in a test-driven development process with Go.
Getting Ready to Test
We'll build a WeatherAlertService that fetches data from a WeatherService. This service will issue alerts based on specific conditions. Relying on the actual data source is impractical for testing, so we'll use stubbed data instead.
Red: Writing the First Test
Create a new test file named weather_alert_service_test.go with the following test setup:
In this test:
- We create a manual stub
WeatherServiceStubthat simulates weather data by setting predefined values forTemperatureandConditionsvia theSetWeathermethod. - The stub’s
GetCurrentWeathermethod returns aWeatherDatastruct with these predefined values, simulating expected weather conditions for the test scenario. - The Testify library is used to assert whether the
WeatherAlertServicecorrectly interprets the weather data and returns the appropriate alert, specifically checking for a heat warning when the temperature exceeds 35 degrees.
Run this test, expecting it to fail initially, as WeatherAlertService has yet to implement the logic for handling these conditions.
