install
sudo apt install libgtest-dev
installation check
dpkg -l | grep gtest
# or
apt list --installed | grep gtest
check GTest headers
ls /usr/include/gtest/gtest.h
# or
find /usr -name "gtest.h" 2>/dev/null
Check if GTest is available using pkg-config
pkg-config --modversion gtest
application
simple application
cmake_minimum_required(VERSION 3.10)
project(MyTestProject)
# Enable testing: Without calling `enable_testing()`, you cannot use the `add_test()` command, and testing features will not be available in your project.
enable_testing()
# Find Google Test
find_package(GTest REQUIRED)
# Include directories for Google Test
include_directories(${GTEST_INCLUDE_DIRS})
# Add your test source file
add_executable(my_tests my_tests.cpp)
# Link Google Test libraries
target_link_libraries(my_tests GTest::GTest GTest::Main)
# target_link_libraries(my_tests gtest gtest_main)
# Add the test to CTest: registers a test with the CMake testing system; You can define and run multiple tests in an organized way; Works seamlessly with continuous integration systems to automate testing pipelines; You can pass specific arguments to your test binary.
add_test(NAME MyTests COMMAND my_tests)
#include <gtest/gtest.h>
TEST(Test, test1)
{
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
# run a specific test
./test_example --gtest_filter=AdditionTest.PositiveNumbers
# Run all tests except one
./test_example --gtest_filter=-AdditionTest.PositiveNumbers
Using Environment Variables for Custom Behaviors
#include <cstdlib> // For std::setenv
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
if (result != 0) {
std::setenv("GTEST_FAILED", "1", 1); // Set an environment variable
}
return result;
}
Then, in a shell script or CI/CD pipeline, you can check:
if [ "$GTEST_FAILED" == "1" ]; then
echo "Tests failed"
exit 1
fi
assertion
Basic Assertions
EXPECT_EQ(val1, val2); // Check if values are equal.
EXPECT_NE(val1, val2); // Check if values are not equal.
EXPECT_LT(val1, val2); // Check if val1 is less than val2.
EXPECT_LE(val1, val2); // Check if val1 is less than or equal to val2.
EXPECT_GT(val1, val2); // Check if val1 is greater than val2.
EXPECT_GE(val1, val2); // Check if val1 is greater than or equal to val2.
Fatal Assertions (Stops Test Immediately)
ASSERT_EQ(val1, val2)
ASSERT_NE(val1, val2)
ASSERT_TRUE(condition)
ASSERT_FALSE(condition)
Returning Different Exit Codes Based on Failure Count
#include <gtest/gtest.h>
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
if (testing::UnitTest::GetInstance()->failed_test_count() > 5)
{
return 10; // Return a specific code if more than 5 tests fail
}
return result; // Default behavior otherwise
}
This approach helps distinguish between minor and major failures.