CodeBlanks Logo Icon CodeBlanks

Summary - Testing basics

Combine TEST, ASSERT and Mock to write a calculator test.

Summary: combining test tools

In this summary you will combine the TEST macro, the ASSERT/EXPECT split and fixtures in a calculator test. You will first write a Calc class, then set up shared setup with a fixture and test it with TEST_F.

The Calc class has an add(int, int) method. The CalcTest fixture prepares a Calc object in SetUp. Inside TEST_F(CalcTest, Adds) call EXPECT_EQ(calc.add(2, 3), 5). This way fixture, test and assertion work together; it is a small example of real project test structure.

Practice Write the calculator test

Define a Calc class with public int add(int a, int b) { return a + b; }. Derive a CalcTest fixture from ::testing::Test; in SetUp prepare a Calc calc; member. Inside TEST_F(CalcTest, Adds) call EXPECT_EQ(calc.add(2, 3), 5). In main print std::cout << "test: ready";.

Starter code

main.cpp
#include <iostream>
#include <gtest/gtest.h>

// Define the Calc class
// Add the CalcTest fixture and TEST_F macro

int main(int argc, char** argv) {
    std::cout << "test: ready";
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <gtest/gtest.h>

class Calc {
public:
    int add(int a, int b) { return a + b; }
};

class CalcTest : public ::testing::Test {
protected:
    void SetUp() override {
        calc = Calc();
    }
    Calc calc;
};

TEST_F(CalcTest, Adds) {
    EXPECT_EQ(calc.add(2, 3), 5);
}

int main(int argc, char** argv) {
    std::cout << "test: ready";
    return 0;
}

Expected output

test: ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What do fixtures and mocks provide together?

  • Faster compilation
  • Shared setup and isolated dependencies Correct answer
  • Colored output
  • Fewer lines of code

Explanation: Fixtures give shared setup; mocks isolate dependencies.

2 Complete the TEST_F call

Question
____(CalcTest, Adds) {
    EXPECT_EQ(calc.add(2, 3), 5);
}
Answer
TEST_F(CalcTest, Adds) {
    EXPECT_EQ(calc.add(2, 3), 5);
}

Explanation: TEST_F defines a test with a fixture.

3 Match the tool to its role

Term Meaning
TEST Defines a simple test
TEST_F Defines a fixture test
EXPECT_EQ Checks equality
MOCK_METHOD Creates a fake method

All lessons in Advanced