Language: CPP
Testing
Google Test was created by Google engineers to provide a standardized and efficient way to write C++ unit tests. It supports both small-scale and large-scale projects, integrating well with CI pipelines and offering detailed test reporting.
Google Test (gtest) is a robust C++ unit testing framework developed by Google. It provides a rich set of assertions, test fixtures, parameterized tests, and utilities to help write reliable and maintainable tests.
sudo apt install libgtest-dev && cd /usr/src/gtest && sudo cmake . && sudo make && sudo cp *.a /usr/libbrew install googletestDownload from https://github.com/google/googletest and build using CMakeGoogle Test allows writing unit tests using `TEST` and `TEST_F` macros. It provides assertions like `EXPECT_EQ`, `ASSERT_TRUE`, `EXPECT_THROW`, supports test fixtures for shared setup/teardown, and parameterized tests for testing multiple inputs.
#include <gtest/gtest.h>
int Add(int a, int b) {
return a + b;
}
TEST(MathTest, AddPositiveNumbers) {
EXPECT_EQ(Add(2, 3), 5);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}Defines a simple test case that checks if `Add(2, 3)` returns 5 using `EXPECT_EQ`.
TEST(MathTest, DivideTest) {
int x = 10;
int y = 2;
ASSERT_NE(y, 0); // stops test if y is zero
EXPECT_EQ(x / y, 5); // continues even if this fails
}`ASSERT_` stops the test immediately if the assertion fails, while `EXPECT_` continues execution.
class MyTest : public ::testing::Test {
protected:
void SetUp() override {
value = 10;
}
int value;
};
TEST_F(MyTest, CheckValue) {
EXPECT_EQ(value, 10);
}Uses a test fixture for shared setup. `TEST_F` accesses members defined in the fixture.
class FactorialTest : public ::testing::TestWithParam<std::pair<int,int>> {};
TEST_P(FactorialTest, HandlesFactorial) {
auto [input, expected] = GetParam();
EXPECT_EQ(Factorial(input), expected);
}
INSTANTIATE_TEST_SUITE_P(FactorialTests, FactorialTest, ::testing::Values(
std::make_pair(0,1), std::make_pair(1,1), std::make_pair(3,6)
));Runs the same test with multiple input/output pairs using parameterized tests.
TEST(ExceptionTest, ThrowsWhenNegative) {
EXPECT_THROW(FunctionThatThrows(-1), std::invalid_argument);
}Checks that the function throws an exception of the expected type.
Use `EXPECT_` for non-critical checks and `ASSERT_` for critical preconditions.
Organize tests into logical test suites using `TEST` and `TEST_F`.
Keep tests small, focused, and independent from each other.
Use parameterized tests to cover multiple scenarios efficiently.
Integrate Google Test with CI/CD pipelines for automated testing.