Using Stubs in C++ with Google Test and Google Mock for Test-Driven Development

Introduction and Context Setting

Welcome to the second lesson in our exploration of Test-Driven Development (TDD) using C++ with Google Test and Google Mock. In the previous lesson, we covered how to utilize dummies to isolate dependencies. In this lesson, we will focus on 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++ testing ecosystem.

Understanding Stubs in Testing

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++, Google Mock 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.

Example: Crafting a `WeatherAlertService` Using Stubs

To illustrate the concept of stubs, we will create a WeatherAlertService using stubs in a test-driven development process.

Getting Ready to Test

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.

Red: Writing the First Test

Create a new test file named WeatherAlertServiceTests.cpp with the following test setup:

C++
#include <gtest/gtest.h>

class WeatherServiceStub {
public:
    void SetWeather(int temperature, const std::string& conditions) {
        this->temperature = temperature;
        this->conditions = conditions;
    }

    virtual ~WeatherServiceStub() = default;

    WeatherData GetCurrentWeather(const std::string& location) {
        return {temperature, conditions};
    }

private:
    int temperature = 20;
    std::string conditions = "sunny";
};

class WeatherAlertService {
public:
    explicit WeatherAlertService(WeatherServiceStub* weatherService)
        : weatherService(weatherService) {}

    std::string ShouldSendAlert(const std::string& location) {
        auto weather = weatherService->GetCurrentWeather(location);
        if (weather.temperature > 35) {
            return "Extreme heat warning. Stay hydrated!";
        }
        return {};
    }

private:
    WeatherServiceStub* weatherService;
};

class WeatherAlertServiceTests : public ::testing::Test {
protected:
    WeatherServiceStub weatherService;
    WeatherAlertService alertService{&weatherService};

    WeatherAlertServiceTests() = default;
    ~WeatherAlertServiceTests() override = default;
};

TEST_F(WeatherAlertServiceTests, ShouldReturnHeatWarningWhenTemperatureIsAbove35) {
    // Arrange
    weatherService.SetWeather(36, "sunny");

    // Act
    auto alert = alertService.ShouldSendAlert("London");

    // Assert
    EXPECT_EQ("Extreme heat warning. Stay hydrated!", alert);
}

In this test:

  • We create a stub WeatherServiceStub with methods SetWeather and GetCurrentWeather that provide predefined values, simulating the expected weather conditions.
  • We validate whether the WeatherAlertService 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.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal