### Example pkg-config file content Source: https://google.github.io/googletest/pkgconfig.html The structure of a generated gtest.pc file. ```text libdir=/usr/lib64 includedir=/usr/include Name: gtest Description: GoogleTest (without main() function) Version: 1.11.0 URL: https://github.com/google/googletest Libs: -L${libdir} -lgtest -lpthread Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread ``` -------------------------------- ### Configure cross-compilation installation Source: https://google.github.io/googletest/pkgconfig.html Commands to install GoogleTest into a specific sysroot directory for cross-compilation. ```bash mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr .. ``` ```bash make -j install DESTDIR=/home/MYUSER/sysroot ``` -------------------------------- ### Declare a function for testing Source: https://google.github.io/googletest/primer.html Example of a function signature to be tested. ```cpp int Factorial(int n); // Returns the factorial of n ``` -------------------------------- ### Implement and Use a Predicate Formatter Source: https://google.github.io/googletest/reference/assertions.html Example implementation of a custom predicate-formatter and its usage with EXPECT_PRED_FORMAT2. ```cpp // Returns the smallest prime common divisor of m and n, // or 1 when m and n are mutually prime. int SmallestPrimeCommonDivisor(int m, int n) { ... } // Returns true if m and n have no common divisors except 1. bool MutuallyPrime(int m, int n) { ... } // A predicate-formatter for asserting that two integers are mutually prime. testing::AssertionResult AssertMutuallyPrime(const char* m_expr, const char* n_expr, int m, int n) { if (MutuallyPrime(m, n)) return testing::AssertionSuccess(); return testing::AssertionFailure() << m_expr << " and " << n_expr << " (" << m << " and " << n << ") are not mutually prime, " << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); } ... const int a = 3; const int b = 4; const int c = 10; ... EXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b); // Succeeds EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); // Fails ``` -------------------------------- ### Example Failure Message with Trace Source: https://google.github.io/googletest/advanced.html Shows how the trace information appears in the test output. ```text path/to/foo_test.cc:11: Failure Value of: Bar(n) Expected: 1 Actual: 2 Google Test trace: path/to/foo_test.cc:17: A path/to/foo_test.cc:12: Failure Value of: Bar(n + 1) Expected: 2 Actual: 3 ``` -------------------------------- ### Basic gMock Workflow Example Source: https://google.github.io/googletest/gmock_cheat_sheet.html Demonstrates the typical lifecycle of a mock object, including setting default actions and defining expectations. ```cpp using ::testing::Return; // #1 TEST(BarTest, DoesThis) { MockFoo foo; // #2 ON_CALL(foo, GetSize()) // #3 .WillByDefault(Return(1)); // ... other default actions ... EXPECT_CALL(foo, Describe(5)) // #4 .Times(3) .WillRepeatedly(Return("Category 5")); // ... other expectations ... EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5 } // #6 ``` -------------------------------- ### Basic Mock Usage Example Source: https://google.github.io/googletest/gmock_for_dummies.html Demonstrates the standard workflow of creating a mock object and setting an expectation that a method is called at least once. ```cpp #include "path/to/mock-turtle.h" #include #include using ::testing::AtLeast; // #1 TEST(PainterTest, CanDrawSomething) { MockTurtle turtle; // #2 EXPECT_CALL(turtle, PenDown()) // #3 .Times(AtLeast(1)); Painter painter(&turtle); // #4 EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); // #5 } ``` -------------------------------- ### Incorrect Loop-based Expectation Setup Source: https://google.github.io/googletest/gmock_for_dummies.html An example of how sticky expectations can cause errors when defined inside a loop. ```cpp using ::testing::Return; ... for (int i = n; i > 0; i--) { EXPECT_CALL(turtle, GetX()) .WillOnce(Return(10*i)); } ``` -------------------------------- ### Verify Predicate Logic Source: https://google.github.io/googletest/reference/assertions.html Example of using EXPECT_PRED2 to verify a custom boolean function. ```cpp // Returns true if m and n have no common divisors except 1. bool MutuallyPrime(int m, int n) { ... } ... const int a = 3; const int b = 4; const int c = 10; ... EXPECT_PRED2(MutuallyPrime, a, b); // Succeeds EXPECT_PRED2(MutuallyPrime, b, c); // Fails ``` -------------------------------- ### Dynamic Test Registration Example Source: https://google.github.io/googletest/advanced.html Implementation of a custom fixture and test class with dynamic registration using a lambda factory. ```cpp class MyFixture : public testing::Test { public: // All of these optional, just like in regular macro usage. static void SetUpTestSuite() { ... } static void TearDownTestSuite() { ... } void SetUp() override { ... } void TearDown() override { ... } }; class MyTest : public MyFixture { public: explicit MyTest(int data) : data_(data) {} void TestBody() override { ... } private: int data_; }; void RegisterMyTests(const std::vector& values) { for (int v : values) { testing::RegisterTest( "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, std::to_string(v).c_str(), __FILE__, __LINE__, // Important to use the fixture type as the return type here. [=]() -> MyFixture* { return new MyTest(v); }); } } ... int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); std::vector values_to_test = LoadValuesFromConfig(); RegisterMyTests(values_to_test); ... return RUN_ALL_TESTS(); } ``` -------------------------------- ### Instantiate ScopedTrace Source: https://google.github.io/googletest/reference/testing.html Example of creating a ScopedTrace instance to include trace information in test failure messages. ```cpp testing::ScopedTrace trace("file.cc", 123, "message"); ``` -------------------------------- ### Streaming messages to ASSERT_EQ Source: https://google.github.io/googletest/faq.html Example of streaming custom messages to an assertion macro. ```cpp ASSERT_EQ(1, Foo()) << "blah blah" << foo; ``` -------------------------------- ### Value-Parameterized Test Instance Creation Source: https://google.github.io/googletest/faq.html Examples of how value-parameterized tests handle different instantiation patterns for implementations. ```cpp new Foo ``` ```cpp new Bar(5) ``` -------------------------------- ### Example failure message for EXPECT_THAT Source: https://google.github.io/googletest/reference/assertions.html Displays the output format when an EXPECT_THAT assertion fails. ```text Value of: value1 Actual: "Hi, world!" Expected: starts with "Hello" ``` -------------------------------- ### Sample JSON Report Output Source: https://google.github.io/googletest/advanced.html An example of the JSON output generated by the sample test program. ```json { "tests": 3, "failures": 1, "errors": 0, "time": "0.035s", "timestamp": "2011-10-31T18:52:42Z", "name": "AllTests", "testsuites": [ { "name": "MathTest", "tests": 2, "failures": 1, "errors": 0, "time": "0.015s", "testsuite": [ { "name": "Addition", "file": "test.cpp", "line": 1, "status": "RUN", "time": "0.007s", "classname": "", "failures": [ { "message": "Value of: add(1, 1)\n Actual: 3\nExpected: 2", "type": "" }, { "message": "Value of: add(1, -1)\n Actual: 1\nExpected: 0", "type": "" } ] }, { "name": "Subtraction", "file": "test.cpp", "line": 2, "status": "RUN", "time": "0.005s", "classname": "" } ] }, { "name": "LogicTest", "tests": 1, "failures": 0, "errors": 0, "time": "0.005s", "testsuite": [ { "name": "NonContradiction", "file": "test.cpp", "line": 3, "status": "RUN", "time": "0.005s", "classname": "" } ] } ] } ``` -------------------------------- ### Typed Test Instance Creation Source: https://google.github.io/googletest/faq.html Examples of how typed tests can instantiate implementations using a common pattern. ```cpp new TypeParam ``` ```cpp CreateInstance() ``` -------------------------------- ### Example GoogleTest Program Source: https://google.github.io/googletest/advanced.html A sample set of test definitions used to demonstrate XML report generation. ```cpp TEST(MathTest, Addition) { ... } TEST(MathTest, Subtraction) { ... } TEST(LogicTest, NonContradiction) { ... } ``` -------------------------------- ### List available tests Source: https://google.github.io/googletest/advanced.html Example output format when running a test program with the --gtest_list_tests flag. ```text TestSuite1. TestName1 TestName2 TestSuite2. TestName ``` -------------------------------- ### Using Matchers in Expectations Source: https://google.github.io/googletest/gmock_for_dummies.html Examples of using matchers to define expected arguments, including specific values, wildcards, and predicates. ```cpp // Expects the turtle to move forward by 100 units. EXPECT_CALL(turtle, Forward(100)); ``` ```cpp using ::testing::_; ... // Expects that the turtle jumps to somewhere on the x=50 line. EXPECT_CALL(turtle, GoTo(50, _)); ``` ```cpp using ::testing::Ge; ... // Expects the turtle moves forward by at least 100. EXPECT_CALL(turtle, Forward(Ge(100))); ``` ```cpp // Expects the turtle to move forward. EXPECT_CALL(turtle, Forward); // Expects the turtle to jump somewhere. EXPECT_CALL(turtle, GoTo); ``` -------------------------------- ### Define a Queue interface Source: https://google.github.io/googletest/primer.html Example interface for a FIFO queue class used for testing. ```cpp template // E is the element type. class Queue { public: Queue(); void Enqueue(const E& element); E* Dequeue(); // Returns NULL if the queue is empty. size_t size() const; ... }; ``` -------------------------------- ### GoogleTest Terminal Output Example Source: https://google.github.io/googletest/advanced.html A sample of the terminal output generated by GoogleTest during test execution. ```text ... [----------] 1 test from FooTest [ RUN ] FooTest.DoesAbc [ OK ] FooTest.DoesAbc [----------] 2 tests from BarTest [ RUN ] BarTest.HasXyzProperty [ OK ] BarTest.HasXyzProperty [ RUN ] BarTest.ReturnsTrueOnSuccess ... some error messages ... [ FAILED ] BarTest.ReturnsTrueOnSuccess ... [==========] 30 tests from 14 test suites ran. [ PASSED ] 28 tests. [ FAILED ] 2 tests, listed below: [ FAILED ] BarTest.ReturnsTrueOnSuccess [ FAILED ] AnotherTest.DoesXyz 2 FAILED TESTS ``` -------------------------------- ### Demonstrating Test Name Collisions Source: https://google.github.io/googletest/faq.html Example showing how underscores in test names can lead to identical generated class names. ```cpp TEST(Time, Flies_Like_An_Arrow) { ... } TEST(Time_Flies, Like_An_Arrow) { ... } ``` -------------------------------- ### Interface Type Casting Source: https://google.github.io/googletest/faq.html Example of ensuring an implementation satisfies the interface type. ```cpp implicit_cast(my_concrete_impl) ``` -------------------------------- ### Example Opaque Assertion Output Source: https://google.github.io/googletest/advanced.html The default output when using a standard boolean predicate. ```text Value of: IsEven(Fib(4)) Actual: false Expected: true ``` -------------------------------- ### Mock Failure Output Example Source: https://google.github.io/googletest/gmock_for_dummies.html Shows the error message format generated by gMock when an expectation is not met during test execution. ```text path/to/my_test.cc:119: Failure Actual function call count doesn't match this expectation: Actually: never called; Expected: called at least once. Stack trace: ... ``` -------------------------------- ### Example Test Functions for Sharding Source: https://google.github.io/googletest/advanced.html A set of test functions used to demonstrate how GoogleTest distributes work across multiple shards. ```cpp TEST(A, V) TEST(A, W) TEST(B, X) TEST(B, Y) TEST(B, Z) ``` -------------------------------- ### Example Failed Assertion Output Source: https://google.github.io/googletest/advanced.html The output generated when using an AssertionResult-based predicate. ```text Value of: IsEven(Fib(4)) Actual: false (3 is odd) Expected: true ``` -------------------------------- ### Generated XML Report Output Source: https://google.github.io/googletest/advanced.html An example of the XML output generated by the provided test program. ```xml ... ... ``` -------------------------------- ### Example of SCOPED_TRACE in Sub-routines Source: https://google.github.io/googletest/advanced.html Demonstrates how SCOPED_TRACE provides context for failures within a sub-routine call. ```cpp 10: void Sub1(int n) { 11: EXPECT_EQ(Bar(n), 1); 12: EXPECT_EQ(Bar(n + 1), 2); 13: } 14: 15: TEST(FooTest, Bar) { 16: { 17: SCOPED_TRACE("A"); // This trace point will be included in 18: // every failure in this scope. 19: Sub1(1); 20: } 21: // Now it won't. 22: Sub1(9); 23: } ``` -------------------------------- ### Predicate Formatter Failure Message Output Source: https://google.github.io/googletest/reference/assertions.html The resulting failure message produced by the AssertMutuallyPrime example. ```text b and c (4 and 10) are not mutually prime, as they have a common divisor 2 ``` -------------------------------- ### Use With clause for multi-argument matching Source: https://google.github.io/googletest/reference/mocking.html Example of using the With clause to restrict default behavior based on a relationship between two arguments. ```cpp using ::testing::_; using ::testing::Lt; using ::testing::Return; ... ON_CALL(my_mock, SetPosition(_, _)) .With(Lt()) .WillByDefault(Return(true)); ``` -------------------------------- ### Define a Mock Class with MOCK_METHOD Source: https://google.github.io/googletest/gmock_for_dummies.html Example of a mock class implementation using the MOCK_METHOD macro to override virtual methods from a base interface. ```cpp #include // Brings in gMock. class MockTurtle : public Turtle { public: ... MOCK_METHOD(void, PenUp, (), (override)); MOCK_METHOD(void, PenDown, (), (override)); MOCK_METHOD(void, Forward, (int distance), (override)); MOCK_METHOD(void, Turn, (int degrees), (override)); MOCK_METHOD(void, GoTo, (int x, int y), (override)); MOCK_METHOD(int, GetX, (), (const, override)); MOCK_METHOD(int, GetY, (), (const, override)); }; ``` -------------------------------- ### Using With Clause for Multi-argument Matching Source: https://google.github.io/googletest/reference/mocking.html Example of restricting an expectation using the With clause to compare multiple arguments. ```cpp using ::testing::_; using ::testing::Lt; ... EXPECT_CALL(my_mock, SetPosition(_, _)) .With(Lt()); ``` -------------------------------- ### Defining Complex Expectations Source: https://google.github.io/googletest/gmock_for_dummies.html An example of chaining multiple actions to define specific return values over several calls. ```cpp using ::testing::Return; ... EXPECT_CALL(turtle, GetX()) .Times(5) .WillOnce(Return(100)) .WillOnce(Return(150)) .WillRepeatedly(Return(200)); ``` -------------------------------- ### Example Negative Assertion Output Source: https://google.github.io/googletest/advanced.html The output generated when using an AssertionResult with a success message in a negative assertion. ```text Value of: IsEven(Fib(6)) Actual: true (8 is even) Expected: false ``` -------------------------------- ### Test private members with FRIEND_TEST Source: https://google.github.io/googletest/advanced.html Example showing the declaration of a friend test in a header file and its subsequent usage in a test file. ```cpp // foo.h class Foo { ... private: FRIEND_TEST(FooTest, BarReturnsZeroOnNull); int Bar(void* x); }; // foo_test.cc ... TEST(FooTest, BarReturnsZeroOnNull) { Foo foo; EXPECT_EQ(foo.Bar(NULL), 0); // Uses Foo's private member Bar(). } ``` -------------------------------- ### Define a Global Test Environment Source: https://google.github.io/googletest/advanced.html Subclass testing::Environment to implement custom SetUp and TearDown logic for the entire test program. ```cpp class Environment : public ::testing::Environment { public: ~Environment() override {} // Override this to define how to set up the environment. void SetUp() override {} // Override this to define how to tear down the environment. void TearDown() override {} }; ``` -------------------------------- ### Initialize Project Directory Source: https://google.github.io/googletest/quickstart-cmake.html Create and enter a new directory for the project. ```bash $ mkdir my_project && cd my_project ``` -------------------------------- ### Initialize Bazel workspace Source: https://google.github.io/googletest/quickstart-bazel.html Create a new directory for the project and navigate into it. ```bash $ mkdir my_workspace && cd my_workspace ``` -------------------------------- ### Define a mock method with a const parameter in MSVC Source: https://google.github.io/googletest/gmock_faq.html Example of a mock method definition that may trigger MSVC warnings C4301 or C4373 due to const parameter qualifiers. ```cpp class Foo { ... virtual void Bar(const int i) = 0; }; class MockFoo : public Foo { ... MOCK_METHOD(void, Bar, (const int i), (override)); }; ``` -------------------------------- ### Configure CMakeLists.txt Source: https://google.github.io/googletest/quickstart-cmake.html Define project requirements and fetch GoogleTest using the FetchContent module. ```cmake cmake_minimum_required(VERSION 3.14) project(my_project) # GoogleTest requires at least C++17 set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) include(FetchContent) FetchContent_Declare( googletest URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip ) # For Windows: Prevent overriding the parent project's compiler/linker settings set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) FetchContent_MakeAvailable(googletest) ``` -------------------------------- ### Share resources using SetUpTestSuite and TearDownTestSuite Source: https://google.github.io/googletest/advanced.html Define static members and static setup/teardown methods to share expensive resources across all tests in a fixture class. ```cpp class FooTest : public testing::Test { protected: // Per-test-suite set-up. // Called before the first test in this test suite. // Can be omitted if not needed. static void SetUpTestSuite() { shared_resource_ = new ...; // If `shared_resource_` is **not deleted** in `TearDownTestSuite()`, // reallocation should be prevented because `SetUpTestSuite()` may be called // in subclasses of FooTest and lead to memory leak. // // if (shared_resource_ == nullptr) { // shared_resource_ = new ...; // } } // Per-test-suite tear-down. // Called after the last test in this test suite. // Can be omitted if not needed. static void TearDownTestSuite() { delete shared_resource_; shared_resource_ = nullptr; } // You can define per-test set-up logic as usual. void SetUp() override { ... } // You can define per-test tear-down logic as usual. void TearDown() override { ... } // Some expensive resource shared by all tests. static T* shared_resource_; }; T* FooTest::shared_resource_ = nullptr; TEST_F(FooTest, Test1) { ... you can refer to shared_resource_ here ... } TEST_F(FooTest, Test2) { ... you can refer to shared_resource_ here ... } ``` -------------------------------- ### Build and run tests Source: https://google.github.io/googletest/quickstart-bazel.html Execute the test target with C++17 optimization flags. ```bash **$ bazel test --cxxopt=-std=c++17 --test_output=all //:hello_test** INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured). INFO: Found 1 test target... INFO: From Testing //:hello_test: ==================== Test output for //:hello_test: Running main() from gmock_main.cc [==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from HelloTest [ RUN ] HelloTest.BasicAssertions [ OK ] HelloTest.BasicAssertions (0 ms) [----------] 1 test from HelloTest (0 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test suite ran. (0 ms total) [ PASSED ] 1 test. ================================================================================ Target //:hello_test up-to-date: bazel-bin/hello_test INFO: Elapsed time: 4.190s, Critical Path: 3.05s INFO: 27 processes: 8 internal, 19 linux-sandbox. INFO: Build completed successfully, 27 total actions //:hello_test PASSED in 0.1s INFO: Build completed successfully, 27 total actions ``` -------------------------------- ### Create Test File Source: https://google.github.io/googletest/quickstart-cmake.html Define a basic test case using the GoogleTest framework. ```cpp #include // Demonstrate some basic assertions. TEST(HelloTest, BasicAssertions) { // Expect two strings not to be equal. EXPECT_STRNE("hello", "world"); // Expect equality. EXPECT_EQ(7 * 6, 42); } ``` -------------------------------- ### Define BUILD file Source: https://google.github.io/googletest/quickstart-bazel.html Declare the test binary and link the required GoogleTest libraries. ```starlark cc_test( name = "hello_test", size = "small", srcs = ["hello_test.cc"], deps = [ "@googletest//:gtest", "@googletest//:gtest_main", ], ) ``` -------------------------------- ### Instantiate test suite with heterogeneous types Source: https://google.github.io/googletest/reference/testing.html Demonstrates using Values() with heterogeneous argument types that are implicitly convertible to the fixture parameter type. ```cpp INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite, testing::Values(1, 1.2)); // Yes, Values() supports heterogeneous argument types. ``` -------------------------------- ### Register Environment via Global Variable Source: https://google.github.io/googletest/advanced.html Register an environment using a global variable, though writing a custom main() is recommended to avoid initialization order issues. ```cpp testing::Environment* const foo_env = testing::AddGlobalTestEnvironment(new FooEnvironment); ``` -------------------------------- ### Build and Run Tests Source: https://google.github.io/googletest/quickstart-cmake.html Commands to configure, build, and execute tests using CMake and ctest. ```bash **my_project$ cmake -S . -B build** -- The C compiler identification is GNU 10.2.1 -- The CXX compiler identification is GNU 10.2.1 ... -- Build files have been written to: .../my_project/build **my_project$ cmake --build build** Scanning dependencies of target gtest ... [100%] Built target gmock_main **my_project$ cd build && ctest** Test project .../my_project/build Start 1: HelloTest.BasicAssertions 1/1 Test #1: HelloTest.BasicAssertions ........ Passed 0.00 sec 100% tests passed, 0 tests failed out of 1 Total Test time (real) = 0.01 sec ``` -------------------------------- ### Troubleshoot pkg-config path Source: https://google.github.io/googletest/pkgconfig.html Set the PKG_CONFIG_PATH environment variable if pkg-config fails to locate the GoogleTest .pc files. ```bash export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig ``` -------------------------------- ### Use WillByDefault clause Source: https://google.github.io/googletest/reference/mocking.html Example of specifying a default return value for a mock method using WillByDefault. ```cpp using ::testing::Return; ... ON_CALL(my_mock, Greet()) .WillByDefault(Return("hello")); ``` -------------------------------- ### Demonstrate default action behavior Source: https://google.github.io/googletest/gmock_for_dummies.html Illustrates that default actions are used when the number of calls exceeds the number of WillOnce clauses. ```cpp using ::testing::Return; ... EXPECT_CALL(turtle, GetY()) .Times(4) .WillOnce(Return(100)); ``` -------------------------------- ### testing::InitGoogleTest Source: https://google.github.io/googletest/reference/testing.html Initializes the GoogleTest framework. This must be called before RUN_ALL_TESTS() to parse command-line flags. ```APIDOC ## void testing::InitGoogleTest(int* argc, char** argv) ## void testing::InitGoogleTest(int* argc, wchar_t** argv) ## void testing::InitGoogleTest() ### Description Initializes GoogleTest. This must be called before calling RUN_ALL_TESTS(). It parses the command line for recognized flags and removes them from argv. ### Parameters - **argc** (int*) - Optional - Pointer to the argument count. - **argv** (char** or wchar_t**) - Optional - Pointer to the argument vector. ``` -------------------------------- ### Define a class with a non-virtual destructor Source: https://google.github.io/googletest/gmock_faq.html Example of a class structure that causes memory leaks when deleted through a base pointer. ```cpp class Base { public: // Not virtual, but should be. ~Base() { ... } ... }; class Derived : public Base { public: ... private: std::string value_层的_; }; ... Base* p = new Derived; ... delete p; // Surprise! ~Base() will be called, but ~Derived() will not // - value_ is leaked. ``` -------------------------------- ### Instantiate Test Suites with Parameters Source: https://google.github.io/googletest/advanced.html Use INSTANTIATE_TEST_SUITE_P at global or namespace scope to generate test instances from a suite using parameter generators. ```cpp INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe, FooTest, testing::Values("meeny", "miny", "moe")); ``` ```cpp constexpr absl::string_view kPets[] = {"cat", "dog"}; INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets)); ``` -------------------------------- ### MSVC warning output examples Source: https://google.github.io/googletest/gmock_faq.html Compiler warnings generated by MSVC when overriding virtual functions with const parameters. ```text warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier ``` ```text warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers ``` -------------------------------- ### Define Types for Typed Tests Source: https://google.github.io/googletest/reference/testing.html Example of using testing::Types to define a list of types for typed or type-parameterized tests. ```cpp testing::Types ``` -------------------------------- ### INSTANTIATE_TEST_SUITE_P Source: https://google.github.io/googletest/reference/testing.html Instantiates a value-parameterized test suite defined with TEST_P. ```APIDOC ## INSTANTIATE_TEST_SUITE_P(InstantiationName, TestSuiteName, param_generator, [name_generator]) ### Description Instantiates the value-parameterized test suite TestSuiteName. InstantiationName is a unique name for the instantiation to distinguish between multiple instantiations. The param_generator provides the values for the test parameters. ``` -------------------------------- ### Set cross-compilation environment variables Source: https://google.github.io/googletest/pkgconfig.html Enable system flags and libraries for pkg-config to prevent stripping of standard prefixes during cross-compilation. ```bash export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes ``` -------------------------------- ### Verify pkg-config output Source: https://google.github.io/googletest/pkgconfig.html Commands to check flags and libraries returned by pkg-config. ```bash $ pkg-config --cflags gtest -DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include $ pkg-config --libs gtest -L/usr/lib64 -lgtest -lpthread ``` -------------------------------- ### Instantiate type-parameterized test suites Source: https://google.github.io/googletest/advanced.html Instantiate the test suite with specific types using INSTANTIATE_TYPED_TEST_SUITE_P, providing a unique prefix for each instance. ```cpp using MyTypes = ::testing::Types; INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); ``` ```cpp INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); ``` -------------------------------- ### Verify cross-compilation pkg-config output Source: https://google.github.io/googletest/pkgconfig.html Verify that the sysroot path is correctly included in the output. ```bash $ pkg-config --cflags gtest -DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include $ pkg-config --libs gtest -L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread ``` -------------------------------- ### Handle Multi-parameter Template Predicates Source: https://google.github.io/googletest/reference/assertions.html Wrapping predicates in parentheses to ensure correct macro argument parsing. ```cpp ASSERT_PRED2((MyPredicate), 5, 0); ``` -------------------------------- ### Configure MODULE.bazel Source: https://google.github.io/googletest/quickstart-bazel.html Define the GoogleTest dependency using the Bazel Central Registry. ```starlark # MODULE.bazel # Choose the most recent version available at # https://registry.bazel.build/modules/googletest bazel_dep(name = "googletest", version = "1.18.0") ``` -------------------------------- ### Splitting test suites for death tests Source: https://google.github.io/googletest/faq.html Demonstrates how to organize tests by splitting a suite into a standard test class and a separate death test alias to maintain clear naming conventions. ```cpp class FooTest : public ::testing::Test { ... }; TEST_F(FooTest, Abc) { ... } TEST_F(FooTest, Def) { ... } using FooDeathTest = FooTest; TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } ``` -------------------------------- ### Configure Death Test Styles in main and Tests Source: https://google.github.io/googletest/advanced.html Demonstrates setting the death test style globally in main() and overriding it for specific test cases. ```cpp int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); GTEST_FLAG_SET(death_test_style, "fast"); return RUN_ALL_TESTS(); } TEST(MyDeathTest, TestOne) { GTEST_FLAG_SET(death_test_style, "threadsafe"); // This test is run in the "threadsafe" style: ASSERT_DEATH(ThisShouldDie(), ""); } TEST(MyDeathTest, TestTwo) { // This test is run in the "fast" style: ASSERT_DEATH(ThisShouldDie(), ""); } ``` -------------------------------- ### Example of conflicting test suite execution order Source: https://google.github.io/googletest/faq.html This snippet illustrates a scenario where interleaving tests based on name rather than test suite would cause execution order conflicts. ```cpp TEST_F(FooTest, AbcDeathTest) { ... } TEST_F(FooTest, Uvw) { ... } TEST_F(BarTest, DefDeathTest) { ... } TEST_F(BarTest, Xyz) { ... } ``` -------------------------------- ### Define call dependencies with After Source: https://google.github.io/googletest/reference/mocking.html Use Expectation objects to ensure a method is called only after specific prerequisites are met. ```cpp using ::testing::Expectation; ... Expectation init_x = EXPECT_CALL(my_mock, InitX()); Expectation init_y = EXPECT_CALL(my_mock, InitY()); EXPECT_CALL(my_mock, Describe()) .After(init_x, init_y); ``` ```cpp using ::testing::ExpectationSet; ... ExpectationSet all_inits; // Collect all expectations of InitElement() calls for (int i = 0; i < element_count; i++) { all_inits += EXPECT_CALL(my_mock, InitElement(i)); } EXPECT_CALL(my_mock, Describe()) .After(all_inits); // Expect Describe() call after all InitElement() calls ``` -------------------------------- ### Add Test Executable to CMake Source: https://google.github.io/googletest/quickstart-cmake.html Configure the build system to compile the test binary and enable test discovery. ```cmake enable_testing() add_executable( hello_test hello_test.cc ) target_link_libraries( hello_test GTest::gtest_main ) include(GoogleTest) gtest_discover_tests(hello_test) ``` -------------------------------- ### Register an event listener in main Source: https://google.github.io/googletest/advanced.html Append a custom listener to the TestEventListeners list before calling RUN_ALL_TESTS. ```cpp int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); // Gets hold of the event listener list. testing::TestEventListeners& listeners = testing::UnitTest::GetInstance()->listeners(); // Adds a listener to the end. GoogleTest takes the ownership. listeners.Append(new MinimalistPrinter); return RUN_ALL_TESTS(); } ``` -------------------------------- ### INSTANTIATE_TYPED_TEST_SUITE_P Source: https://google.github.io/googletest/reference/testing.html Instantiates a type-parameterized test suite with a specific set of types. ```APIDOC ## INSTANTIATE_TYPED_TEST_SUITE_P(InstantiationName, TestSuiteName, Types) ### Description Instantiates the type-parameterized test suite `TestSuiteName`. The test suite must be registered with `REGISTER_TYPED_TEST_SUITE_P`. ### Parameters - **InstantiationName** (string) - A unique name for the instantiation, used as a prefix in test output. - **TestSuiteName** (string) - The name of the test suite to instantiate. - **Types** (Types object) - A `::testing::Types` object representing the list of types to run the tests on. ``` -------------------------------- ### Execute tests using the QueueTest fixture Source: https://google.github.io/googletest/primer.html Test cases utilizing the QueueTest fixture to verify queue operations. ```cpp TEST_F(QueueTest, IsEmptyInitially) { EXPECT_EQ(q0_.size(), 0); } TEST_F(QueueTest, DequeueWorks) { int* n = q0_.Dequeue(); EXPECT_EQ(n, nullptr); n = q1_.Dequeue(); ASSERT_NE(n, nullptr); EXPECT_EQ(*n, 1); EXPECT_EQ(q1_.size(), 0); delete n; n = q2_.Dequeue(); ASSERT_NE(n, nullptr); EXPECT_EQ(*n, 2); EXPECT_EQ(q2_.size(), 1); delete n; } ``` -------------------------------- ### Register a Global Test Environment Source: https://google.github.io/googletest/advanced.html Use AddGlobalTestEnvironment to register an environment instance with GoogleTest. ```cpp Environment* AddGlobalTestEnvironment(Environment* env); ``` -------------------------------- ### Repeat Tests with Command-Line Flags Source: https://google.github.io/googletest/advanced.html Use these commands to execute tests multiple times, optionally stopping on failure or filtering specific tests. ```bash $ foo_test --gtest_repeat=1000 Repeat foo_test 1000 times and don't stop at failures. $ foo_test --gtest_repeat=-1 A negative count means repeating forever. $ foo_test --gtest_repeat=1000 --gtest_break_on_failure Repeat foo_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the test fails, it will drop into the debugger and you can then inspect variables and stacks. $ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.* Repeat the tests whose name matches the filter 1000 times. ``` -------------------------------- ### Configure sysroot for pkg-config Source: https://google.github.io/googletest/pkgconfig.html Set environment variables to ensure pkg-config correctly injects the sysroot path into flags. ```bash export PKG_CONFIG_DIR= export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig ``` -------------------------------- ### General EXPECT_CALL Syntax Source: https://google.github.io/googletest/gmock_for_dummies.html The standard syntax for defining expectations on a mock object method. ```cpp EXPECT_CALL(mock_object, method(matchers)) .Times(cardinality) .WillOnce(action) .WillRepeatedly(action); ``` ```cpp EXPECT_CALL(mock_object, non-overloaded-method) .Times(cardinality) .WillOnce(action) .WillRepeatedly(action); ``` -------------------------------- ### Define sequential return values with WillOnce Source: https://google.github.io/googletest/reference/mocking.html Specify different actions for consecutive calls to the same mock method. ```cpp using ::testing::Return; ... EXPECT_CALL(my_mock, GetNumber()) .WillOnce(Return(1)) .WillOnce(Return(2)) .WillOnce(Return(3)); ``` -------------------------------- ### MATCHER Macro Source: https://google.github.io/googletest/reference/matchers.html Defines a simple matcher without parameters. ```APIDOC ## MATCHER(Name, description) ### Description Defines a matcher that takes no parameters. The body must be a pure function returning a boolean. ### Example MATCHER(IsEven, "") { return (arg % 2) == 0; } ``` -------------------------------- ### Integrate GoogleTest in CMake Source: https://google.github.io/googletest/pkgconfig.html Use pkg-config to locate GoogleTest and configure build targets. Prefer _CFLAGS and _LDFLAGS to ensure all required flags and macros are included. ```cmake find_package(PkgConfig) pkg_search_module(GTEST REQUIRED gtest_main) add_executable(testapp) target_sources(testapp PRIVATE samples/sample3_unittest.cc) target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS}) target_compile_options(testapp PRIVATE ${GTEST_CFLAGS}) enable_testing() add_test(first_and_only_test testapp) ``` -------------------------------- ### Wrap another matcher with ExplainMatchResult Source: https://google.github.io/googletest/reference/matchers.html Uses ExplainMatchResult to delegate matching logic to another matcher. ```cpp MATCHER_P(NestedPropertyMatches, matcher, "") { return ExplainMatchResult(matcher, arg.nested().property(), result_listener); } ``` -------------------------------- ### Implement a QueueTest fixture Source: https://google.github.io/googletest/primer.html A fixture class derived from testing::Test that initializes queue objects for test cases. ```cpp class QueueTest : public testing::Test { protected: QueueTest() { // q0_ remains empty q1_.Enqueue(1); q2_.Enqueue(2); q2_.Enqueue(3); } // ~QueueTest() override = default; Queue q0_; Queue q1_; Queue q2_; }; ``` -------------------------------- ### Custom main function and test fixture boilerplate Source: https://google.github.io/googletest/primer.html Provides a template for defining a test fixture and a custom main entry point for GoogleTest. ```cpp #include "this/package/foo.h" #include namespace my { namespace project { namespace { // The fixture for testing class Foo. class FooTest : public testing::Test { protected: // You can remove any or all of the following functions if their bodies would // be empty. FooTest() { // You can do set-up work for each test here. } ~FooTest() override { // You can do clean-up work that doesn't throw exceptions here. } // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: void SetUp() override { // Code here will be called immediately after the constructor (right // before each test). } void TearDown() override { // Code here will be called immediately after each test (right // before the destructor). } // Class members declared here can be used by all tests in the test suite // for Foo. }; // Tests that the Foo::Bar() method does Abc. TEST_F(FooTest, MethodBarDoesAbc) { const std::string input_filepath = "this/package/testdata/myinputfile.dat"; const std::string output_filepath = "this/package/testdata/myoutputfile.dat"; Foo f; EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0); } // Tests that Foo does Xyz. TEST_F(FooTest, DoesXyz) { // Exercises the Xyz feature of Foo. } } // namespace } // namespace project } // namespace my int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } ``` -------------------------------- ### Implement AssertionResult with Success Message Source: https://google.github.io/googletest/advanced.html Supplying a success message allows for informative output in both EXPECT_TRUE and EXPECT_FALSE assertions. ```cpp testing::AssertionResult IsEven(int n) { if ((n % 2) == 0) return testing::AssertionSuccess() << n << " is even"; else return testing::AssertionFailure() << n << " is odd"; } ``` -------------------------------- ### Verify Exception Handling with Compound Statements Source: https://google.github.io/googletest/reference/assertions.html Demonstrates using a compound statement within an exception assertion macro. ```cpp EXPECT_NO_THROW({ int n = 5; DoSomething(&n); }); ``` -------------------------------- ### Validate exceptions with Throws matchers Source: https://google.github.io/googletest/reference/matchers.html Demonstrates using Throws and ThrowsMessage matchers to verify exception types and messages in lambda expressions. ```cpp auto argument = [] { throw std::runtime_error("error msg"); }; // Checks if the lambda throws a `std::runtime_error`. EXPECT_THAT(argument, Throws()); // Checks if the lambda throws a `std::runtime_error` with a specific message // that matches "error msg". EXPECT_THAT(argument, Throws(Property(&std::runtime_error::what, Eq("error msg")))); // Checks if the lambda throws a `std::runtime_error` with a message that // contains "msg". EXPECT_THAT(argument, ThrowsMessage(HasSubstr("msg"))); ``` -------------------------------- ### Define Multiple Expectations for a Mock Method Source: https://google.github.io/googletest/gmock_for_dummies.html Demonstrates setting multiple expectations where the last matching expectation takes precedence. ```cpp using ::testing::_; using ::testing::AnyNumber; ... EXPECT_CALL(turtle, GoTo(_, _)) // #1 .Times(AnyNumber()); EXPECT_CALL(turtle, GoTo(0, 0)) // #2 .Times(2); ``` -------------------------------- ### Define Multiple Expectations Source: https://google.github.io/googletest/gmock_for_dummies.html Demonstrates how gMock matches expectations in reverse order, where newer rules override older ones. ```cpp using ::testing::_; ... EXPECT_CALL(turtle, Forward(_)); // #1 EXPECT_CALL(turtle, Forward(10)) // #2 .Times(2); ``` -------------------------------- ### Verify value equality with custom failure messages Source: https://google.github.io/googletest/primer.html Demonstrates using ASSERT_EQ and EXPECT_EQ with custom failure messages streamed via the << operator. ```cpp ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; for (int i = 0; i < x.size(); ++i) { EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; } ``` -------------------------------- ### Instantiate a value-parameterized test suite Source: https://google.github.io/googletest/reference/testing.html Configures a parameterized test suite with a generator and an optional custom name generator. ```cpp INSTANTIATE_TEST_SUITE_P( MyInstantiation, MyTestSuite, testing::Values(...), [](const testing::TestParamInfo& info) { // Can use info.param here to generate the test suffix std::string name = ... return name; }); ``` -------------------------------- ### Derive test fixtures in GoogleTest Source: https://google.github.io/googletest/faq.html Demonstrates sharing logic by creating a base test fixture and deriving specific fixtures from it. ```cpp // Defines a base test fixture. class BaseTest : public ::testing::Test { protected: ... }; // Derives a fixture FooTest from BaseTest. class FooTest : public BaseTest { protected: void SetUp() override { BaseTest::SetUp(); // Sets up the base fixture first. ... additional set-up work ... } void TearDown() override { ... clean-up work for FooTest ... BaseTest::TearDown(); // Remember to tear down the base fixture // after cleaning up FooTest! } ... functions and variables for FooTest ... }; // Tests that use the fixture FooTest. TEST_F(FooTest, Bar) { ... } TEST_F(FooTest, Baz) { ... } ... additional fixtures derived from BaseTest ... ``` -------------------------------- ### Custom Pointwise Comparison Source: https://google.github.io/googletest/reference/matchers.html Demonstrates using a custom matcher with Pointwise to compare containers that do not support operator==. ```cpp MATCHER(FooEq, "") { return std::get<0>(arg).Equals(std::get<1>(arg)); } ... EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); ``` -------------------------------- ### Add Traces to Assertions Source: https://google.github.io/googletest/advanced.html Use these macros and utilities to include file and line information in failure messages. ```cpp SCOPED_TRACE(message); ``` ```cpp ScopedTrace trace("file_path", line_number, message); ``` -------------------------------- ### Retrieve current test information Source: https://google.github.io/googletest/advanced.html Use the UnitTest singleton to access the TestInfo object. Ensure the pointer is not deleted as it is managed by the framework. ```cpp // Gets information about the currently running test. // Do NOT delete the returned object - it's managed by the UnitTest class. const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); printf("We are in test %s of test suite %s.\n", test_info->name(), test_info->test_suite_name()); ```