Introduction to Test Driven Development with C++ and Google Test

Introduction to these practices

Welcome to your first lesson in this course dedicated to practicing Test-Driven Development (TDD) utilizing C++ and Google Test/Mock. Test-Driven Development is an effective approach that emphasizes writing tests before coding. This process helps you develop your application around testing, ensuring each component functions as intended. In this lesson, you'll learn the fundamentals of TDD along with the Red-Green-Refactor cycle, understanding their roles in creating consistent and maintainable code.

This course emphasizes hands-on practice, where you'll receive requirements through tests, one at a time. Your task is to implement code that makes each test pass, simulating a real-world TDD environment. Consider this course guide as your pair programmer, providing test-driven prompts to sharpen your skills as you progress.

Understanding the Red-Green-Refactor Cycle

As a reminder, the Red-Green-Refactor cycle is central to TDD, guiding your development process:

  • Red: Start by writing a failing test to define the next step.
  • Green: Implement just enough code to pass the test, focusing on functionality.
  • Refactor: Optimize the code for clarity and efficiency without changing its behavior.

Requirements for `CalculateDiscount` Function

1. Correct Discount Application

  • Description: The function must correctly apply a percentage-based discount to an original price.

  • Test Case:

    #include "gtest/gtest.h"
    
    class MathTests : public ::testing::Test {
    protected:
        Math math;
    };
    
    TEST_F(MathTests, CalculateDiscount_AppliesCorrectDiscount) {
        // Arrange
        double originalPrice = 100;
        double discountPercentage = 20;
        double expectedDiscountedPrice = 80;
    
        // Act
        double result = math.CalculateDiscount(originalPrice, discountPercentage);
    
        // Assert
        EXPECT_NEAR(expectedDiscountedPrice, result, 0.1);
    }

2. Zero Discount Handling

  • Description: The function should return the original price when the discount percentage is 0.

  • Test Case:

    TEST_F(MathTests, CalculateDiscount_ReturnsOriginalPriceWhenDiscountIsZero) {
        // Arrange
        double originalPrice = 50;
        double discountPercentage = 0;
    
        // Act
        double result = math.CalculateDiscount(originalPrice, discountPercentage);
    
        // Assert
        EXPECT_EQ(originalPrice, result);
    }
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