Google C++ Testing Framework (GTest)

Google C++ Testing Framework (GTest)

The Google C++ Testing Framework (Google Test or gtest) is an open-source unit testing library for C++ that provides a structured and automated way to write, organize, and run tests.

It allows developers to define test cases using simple macros, perform assertions on code behavior, and automatically report results, making it easier to verify correctness and prevent regressions in C++ software.

Supports automatic test discovery, a rich set of assertions, user-defined assertions, death tests, fatal and non-fatal failures, value- and type-parameterized tests, various options for running the tests, and XML test report generation.

Google's framework for writing C++ tests on a variety of platforms (Linux, Mac OS X, Windows, Cygwin, Windows CE, and Symbian).

When to use Google Test?

• Writing C++ unit tests
• Building production-grade systems
• You need CI/CD test automation
• Working in large codebases

Principles of Effective Unit Testing

• Tests should be independent and repeatable.
• Tests should be well organized and reflect the structure of the tested code.
• Tests should be portable and reusable.
• When tests fail, they should provide as much information about the problem as possible.
• The testing framework should liberate test writers from housekeeping chores and let them focus on the test content.
• Tests should be fast.

How to use Google Test (gtest)?

1. Install / setup (CMake way – most common)

If you're using CMake:

cmake_minimum_required(VERSION 3.10)
project(MyTests)

set(CMAKE_CXX_STANDARD 17)

# Enable GoogleTest
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS})

add_executable(runTests test.cpp)

target_link_libraries(runTests GTest::GTest GTest::Main pthread)

2. Example code under test

math_utils.h
#pragma once

int Add(int a, int b);
int Multiply(int a, int b);
math_utils.cpp
#include "math_utils.h"

int Add(int a, int b) {
    return a + b;
}

int Multiply(int a, int b) {
    return a * b;
}

3. Writing Google Test cases

test.cpp
#include <gtest/gtest.h>
#include "math_utils.h"

// Test for Add function
TEST(MathUtilsTest, AddPositiveNumbers) {
    EXPECT_EQ(Add(2, 3), 5);
}

// Another test case
TEST(MathUtilsTest, AddNegativeNumbers) {
    EXPECT_EQ(Add(-2, -3), -5);
}

// Test for Multiply function
TEST(MathUtilsTest, MultiplyBasic) {
    EXPECT_EQ(Multiply(3, 4), 12);
}

// Demonstrating failure handling
TEST(MathUtilsTest, IntentionalFailureExample) {
    EXPECT_NE(Add(2, 2), 5);  // should pass
}

4. main() function (optional)

You can either provide your own main or let gtest handle it.

Option A (recommended): let gtest handle main

Option B: custom main

#include <gtest/gtest.h>

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

Contents related to 'Google C++ Testing Framework (GTest)'

CppUnit
CppUnit
How CSharp © 2007 Sitemap, Privacy Policy, Contact