Skip to content

GTest

Programming / cpp

Core Concepts

  • ASSERT_* macros: Fatal failures. If an ASSERT_ fails, current function test will abort immidiately.
  • EXPECT_* macro: Non-fatal failures. If an EXPECT_ fails, current function test continues and allow to find further failures.
  • TEST() macro: defines a function contains assertions to verify a behavior. TEST(TestSuiteName, TestName)

  • TEST_F() macro: Used to define a test fixture. When we need to perform multiple tests on same object TEST_F(FixtureName, TestName)

  • Test Suite: Group of related test


Simple demo

Minimal gtest and CMakeList, for simplicity add the function on test to the test file

test/test_demo.cpp
#include <gtest/gtest.h>

// function for which we write unit tests
int add(int num1, int num2) {
    return num1 + num2;
}

// to test addition of positive numbers
TEST(SumTest, ForPositiveNumbers) {
    EXPECT_EQ(35, add(23, 12));
}

// to test addition of negative numbers
TEST(SumTest, ForNegativeNumbers) {
    EXPECT_EQ(-1, add(-1, 0));
}
cmake_minimum_required(VERSION 3.22)

# Project setup
project(DemoApp VERSION 0.1.0 LANGUAGES CXX)

# Require GoogleTest
find_package(GTest REQUIRED)
include(GoogleTest)

enable_testing()

# defining executable target and its source file
add_executable(
  test_demo
  test/test_demo.cpp
)
# to link the executable with GoogleTest main library
target_link_libraries(
  test_demo
  GTest::gtest_main
)

# to discover and register all tests in the executable
gtest_discover_tests(test_demo)

usage

# -S: source folder
# -B: build folder
cmake -S . -B build

# compile
cmake --build build

cd build
# Test
ctest

Disabled test

Add DISABLED prefix to test suit name

1
2
3
4
// to test addition of negative numbers
TEST(DISABLED_SumTest, ForNegativeNumbers) {
    EXPECT_EQ(-1, add(-1, 0));
}
1
2
3
4
5
Test project /home/user/projects/cmake_presets/build
    Start 1: SumTest.ForPositiveNumbers
1/2 Test #1: SumTest.ForPositiveNumbers .......   Passed    0.00 sec
    Start 2: SumTest.ForNegativeNumbers
2/2 Test #2: SumTest.ForNegativeNumbers .......***Not Run (Disabled)   0.00 sec