### Build and Install GoogleTest on Unix-like Systems Source: https://github.com/google/googletest/blob/main/googletest/README.md Build GoogleTest using 'make' after CMake has generated the Makefiles, and then install it system-wide. ```bash make sudo make install # Install in /usr/local/ by default ``` -------------------------------- ### Test Fixture Setup and Teardown Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Methods for performing setup and teardown operations for individual test fixtures. `SetUp` runs before each test, and `TearDown` runs after each test. ```APIDOC ## Test::SetUp ### Description Override this to perform test fixture setup. GoogleTest calls `SetUp()` before running each individual test. ### Method virtual void ### Signature `virtual void Test::SetUp()` ``` ```APIDOC ## Test::TearDown ### Description Override this to perform test fixture teardown. GoogleTest calls `TearDown()` after running each individual test. ### Method virtual void ### Signature `virtual void Test::TearDown()` ``` -------------------------------- ### Install Project Targets Source: https://github.com/google/googletest/blob/main/googlemock/CMakeLists.txt Installs the Google Mock and Google Mock main libraries, making them available for use in other projects. ```cmake install_project(gmock gmock_main) ``` -------------------------------- ### Example pkg-config file for GoogleTest Source: https://github.com/google/googletest/blob/main/docs/pkgconfig.md This is an example of a pkg-config file for GoogleTest, showing the typical Libdir, Includedir, Libs, and Cflags. ```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 ``` -------------------------------- ### Project Minimum Requirements and Setup Source: https://github.com/google/googletest/blob/main/googlemock/CMakeLists.txt Sets the minimum CMake version and project name, then calls hermetic build setup functions if available. ```cmake cmake_minimum_required(VERSION 3.13) project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) if (COMMAND set_up_hermetic_build) set_up_hermetic_build() endif() ``` -------------------------------- ### Test Suite Setup and Teardown Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Methods for performing setup and teardown operations at the test suite level. `SetUpTestSuite` runs before any tests in the suite, and `TearDownTestSuite` runs after all tests. ```APIDOC ## Test::SetUpTestSuite ### Description Performs shared setup for all tests in the test suite. GoogleTest calls `SetUpTestSuite()` before running the first test in the test suite. ### Method static void ### Signature `static void Test::SetUpTestSuite()` ``` ```APIDOC ## Test::TearDownTestSuite ### Description Performs shared teardown for all tests in the test suite. GoogleTest calls `TearDownTestSuite()` after running the last test in the test suite. ### Method static void ### Signature `static void Test::TearDownTestSuite()` ``` -------------------------------- ### Project Directory Setup Source: https://github.com/google/googletest/blob/main/docs/quickstart-cmake.md Initial command to create a new project directory and navigate into it. ```bash $ mkdir my_project && cd my_project ``` -------------------------------- ### Install GoogleTest Project Source: https://github.com/google/googletest/blob/main/googletest/CMakeLists.txt Installs the GoogleTest project, including the gtest and gtest_main targets. This makes the libraries available for use in other projects. ```cmake install_project(gtest gtest_main) ``` -------------------------------- ### UnitTest::start_timestamp Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the start time of the test program in milliseconds since the Unix epoch. ```APIDOC ## UnitTest::start_timestamp ### Description Gets the time of the test program start, in ms from the start of the UNIX epoch. ### Method `TimeInMillis start_timestamp() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **TimeInMillis**: The start timestamp in milliseconds. ### Response Example N/A ``` -------------------------------- ### Define a Test Environment Source: https://github.com/google/googletest/blob/main/docs/advanced.md Subclass `::testing::Environment` to define custom setup and tear-down logic for your tests. Override `SetUp()` and `TearDown()` methods. ```c++ 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 {} }; ``` -------------------------------- ### Environment Setup and Teardown Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Provides methods for setting up and tearing down the test environment. These are typically overridden by users to customize test execution context. ```APIDOC ## Environment::SetUp ### Description Override this to define how to set up the environment. ### Method virtual void ### Signature `virtual void Environment::SetUp()` ``` ```APIDOC ## Environment::TearDown ### Description Override this to define how to tear down the environment. ### Method virtual void ### Signature `virtual void Environment::TearDown()` ``` -------------------------------- ### Field and Property Matcher Examples Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Illustrates using Field() to match a member's value against a comparison matcher and Property() to match a getter's return value. ```cpp Field(&Foo::number, Ge(3)) ``` ```cpp Property(&Foo::name, StartsWith("John ")) ``` -------------------------------- ### Example Usage of InClosedRange Matcher with Custom Description Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Shows how to use the InClosedRange matcher, which generates a detailed failure message including the range. ```cpp EXPECT_THAT(3, InClosedRange(4, 6)); ``` -------------------------------- ### Example of Programmatic Test Registration in C++ Source: https://github.com/google/googletest/blob/main/docs/advanced.md Demonstrates registering tests dynamically using a lambda factory function. Ensure the factory returns the correct fixture type and is called before RUN_ALL_TESTS(). ```c++ class MyFixture : public testing::Test { public: 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__, [=]() -> 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(); } ``` -------------------------------- ### Per-Test-Suite Setup and Teardown in C++ Source: https://github.com/google/googletest/blob/main/docs/advanced.md Use static SetUpTestSuite() and TearDownTestSuite() methods in your test fixture class to manage resources shared by all tests in a suite. Ensure proper cleanup to avoid memory leaks, especially with inheritance. ```c++ 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 ... } ``` -------------------------------- ### Set up CMakeLists.txt with GoogleTest Dependency Source: https://github.com/google/googletest/blob/main/docs/quickstart-cmake.md Configure your CMake project to declare a dependency on GoogleTest using the FetchContent module. This example specifies a particular commit hash for GoogleTest. ```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) ``` -------------------------------- ### Example Test Functions for Sharding Source: https://github.com/google/googletest/blob/main/docs/advanced.md Illustrates test functions that can be distributed across multiple machines for parallel execution. ```cpp TEST(A, V) TEST(A, W) TEST(B, X) TEST(B, Y) TEST(B, Z) ``` -------------------------------- ### String Starts With Prefix Source: https://github.com/google/googletest/blob/main/docs/reference/matchers.md Use `StartsWith` to verify that a string argument begins with a specified prefix. This is useful for validating headers or formatted strings. ```cpp EXPECT_THAT(actual_string, StartsWith(prefix)); ``` -------------------------------- ### GMock EXPECT_CALL with Return Actions Source: https://github.com/google/googletest/blob/main/docs/gmock_for_dummies.md Demonstrates how to use EXPECT_CALL with Times, WillOnce, and WillRepeatedly clauses to specify return values for a mock method over multiple calls. This example shows a sequence of return values. ```cpp using ::testing::Return; ... EXPECT_CALL(turtle, GetX()) .Times(5) .WillOnce(Return(100)) .WillOnce(Return(150)) .WillRepeatedly(Return(200)); ``` -------------------------------- ### Custom MATCHER example for FooEq Source: https://github.com/google/googletest/blob/main/docs/reference/matchers.md This demonstrates how to define a custom matcher `FooEq` for comparing `Foo` containers that do not support `operator==`, by matching tuples of their elements. ```cpp MATCHER(FooEq, "") { // implementation omitted } ``` -------------------------------- ### Configure Include Directories for GoogleTest Source: https://github.com/google/googletest/blob/main/googletest/CMakeLists.txt Configures system include directories for the gtest and gtest_main targets. Ensures build and install interfaces are correctly set. ```cmake string(REPLACE ";" "$" dirs "${gtest_build_include_dirs}") target_include_directories(gtest SYSTEM INTERFACE "$") target_include_directories(gtest_main SYSTEM INTERFACE "$") ``` -------------------------------- ### Mocking a virtual method in gMock Source: https://github.com/google/googletest/blob/main/docs/gmock_faq.md To mock a method, it must be virtual. This example shows the basic syntax for defining a mock method. ```cpp class Foo { ... virtual void Bar(const int i) = 0; }; class MockFoo : public Foo { ... MOCK_METHOD(void, Bar, (const int i), (override)); }; ``` -------------------------------- ### Set Target Include Directories Source: https://github.com/google/googletest/blob/main/googlemock/CMakeLists.txt Configures include directories for the gmock and gmock_main targets, making them available during build and installation. ```cmake string(REPLACE ";" "$" dirs "${gmock_build_include_dirs}") target_include_directories(gmock SYSTEM INTERFACE "$") target_include_directories(gmock_main SYSTEM INTERFACE "$") ``` -------------------------------- ### Configure Emacs for Google Test and Google Mock Integration Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Add these lines to your ~/.emacs file to enable easy navigation and execution of tests within Emacs. Use M-m to start a build and M-up/M-down to cycle through errors. ```emacs-lisp (global-set-key "\M-m" 'google-compile) ; m is for make (global-set-key [M-down] 'next-error) (global-set-key [M-up] '(lambda () (interactive) (next-error -1))) ``` -------------------------------- ### Basic GMock Test Setup Source: https://github.com/google/googletest/blob/main/docs/gmock_for_dummies.md Demonstrates the typical workflow for using a mock object in a Google Test. Includes importing GMock names, creating a mock object, setting an expectation on a method call, exercising code that uses the mock, and performing assertions. ```cpp #include "path/to/mock-turtle.h" #include #include using ::testing::AtLeast; TEST(PainterTest, CanDrawSomething) { MockTurtle turtle; EXPECT_CALL(turtle, PenDown()) .Times(AtLeast(1)); Painter painter(&turtle); EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); } ``` -------------------------------- ### Define Minimalist Test Event Listener Source: https://github.com/google/googletest/blob/main/docs/advanced.md Create a custom test event listener by subclassing EmptyTestEventListener and overriding specific event handlers. This example demonstrates handling test start, test part results, and test end events for custom output. ```c++ class MinimalistPrinter : public testing::EmptyTestEventListener { // Called before a test starts. void OnTestStart(const testing::TestInfo& test_info) override { printf("*** Test %s.%s starting.\n", test_info.test_suite_name(), test_info.name()); } // Called after a failed assertion or a SUCCESS(). void OnTestPartResult(const testing::TestPartResult& test_part_result) override { printf("%s in %s:%d\n%s\n", test_part_result.failed() ? "*** Failure" : "Success", test_part_result.file_name(), test_part_result.line_number(), test_part_result.summary()); } // Called after a test ends. void OnTestEnd(const testing::TestInfo& test_info) override { printf("*** Test %s.%s ending.\n", test_info.test_suite_name(), test_info.name()); } }; ``` -------------------------------- ### Define Custom Matcher with Custom Failure Message Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md This example shows how to provide a custom string expression for the matcher's description, allowing for more informative failure messages, especially when the matcher is negated. ```cpp MATCHER(IsDivisibleBy7, absl::StrCat(negation ? "isn't" : "is", " divisible by 7")) { return (arg % 7) == 0; } ``` -------------------------------- ### Colored Terminal Output Example Source: https://github.com/google/googletest/blob/main/docs/advanced.md Demonstrates GoogleTest's colored output for distinguishing test statuses and errors. Colors are enabled by default when outputting to a terminal. ```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 ``` -------------------------------- ### Initial Mock Function Definition with Multiple Arguments Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Example of a mock function definition with a complex signature, including various data types and nested structures, to be used in conjunction with argument selection or ignoring techniques. ```cpp using ::testing::_; using ::testing::Invoke; ... MOCK_METHOD(bool, Foo, (bool visible, const string& name, int x, int y, (const map>), double& weight, double min_weight, double max_wight)); ... bool IsVisibleInQuadrant1(bool visible, int x, int y) { return visible && x >= 0 && y >= 0; } ... EXPECT_CALL(mock, Foo) .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( ``` -------------------------------- ### Implement a Polymorphic Action: ReturnSecondArgumentAction Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md This example defines a polymorphic action that returns the second argument of a mock function. The implementation class uses a templated Perform method that can adapt to different function signatures. ```cpp class ReturnSecondArgumentAction { public: template Result Perform(const ArgumentTuple& args) const { // To get the i-th (0-based) argument, use std::get(args). return std::get<1>(args); } }; using ::testing::MakePolymorphicAction; using ::testing::PolymorphicAction; PolymorphicAction ReturnSecondArgument() { return MakePolymorphicAction(ReturnSecondArgumentAction()); } ... MockFoo foo; EXPECT_CALL(foo, DoThis).WillOnce(ReturnSecondArgument()); EXPECT_CALL(foo, DoThat).WillOnce(ReturnSecondArgument()); ... foo.DoThis(true, 5); // Will return 5. foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". ``` -------------------------------- ### Create Composite Predicates with Matchers Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Combine multiple gMock matchers using logical operators like AllOf() to create complex predicates. This example checks if a number is between 0 and 100 (inclusive) and not equal to 50. ```cpp using ::testing::AllOf; using ::testing::Ge; using ::testing::Le; using ::testing::Matches; using ::testing::Ne; ... Matches(AllOf(Ge(0), Le(100), Ne(50))) ``` -------------------------------- ### Example GoogleTest Code Source: https://github.com/google/googletest/blob/main/docs/advanced.md This is an example of C++ code defining GoogleTest test cases. These tests would be executed and their results reflected in the generated XML report. ```c++ TEST(MathTest, Addition) { ... } TEST(MathTest, Subtraction) { ... } TEST(LogicTest, NonContradiction) { ... } ``` -------------------------------- ### Create Bazel Workspace Directory Source: https://github.com/google/googletest/blob/main/docs/quickstart-bazel.md Initializes a new directory for your Bazel workspace. ```bash $ mkdir my_workspace && cd my_workspace ``` -------------------------------- ### Create a GoogleTest Test File Source: https://github.com/google/googletest/blob/main/docs/quickstart-cmake.md Write a basic C++ test file that includes the GoogleTest header and uses basic assertions to verify behavior. ```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); } ``` -------------------------------- ### Example GoogleTest JSON Report Source: https://github.com/google/googletest/blob/main/docs/advanced.md This is an example of a JSON report generated by GoogleTest, illustrating the structure for multiple test suites and individual test cases, including details of a failure. ```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": "" } ] } ] } ``` -------------------------------- ### Example: Duplicate Argument Action Template Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md An example of ACTION_TEMPLATE defining 'DuplicateArg'. This action duplicates a specified argument (k) of the mock function, casting it to a given type (T), and copying it to an output pointer. ```cpp // DuplicateArg(output) converts the k-th argument of the mock // function to type T and copies it to *output. ACTION_TEMPLATE(DuplicateArg, // Note the comma between int and k: HAS_2_TEMPLATE_PARAMS(int, k, typename, T), AND_1_VALUE_PARAMS(output)) { *output = T(std::get(args)); } ``` -------------------------------- ### Example Generated XML Report Source: https://github.com/google/googletest/blob/main/docs/advanced.md This is an example of a detailed XML report generated by GoogleTest for the provided C++ test cases. It includes test durations, failure messages, and source file information. ```xml ... ... ``` -------------------------------- ### UnitTest::total_test_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the total number of tests. ```APIDOC ## UnitTest::total_test_count ### Description Gets the number of all tests. ### Method `int total_test_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The total count of tests. ### Response Example N/A ``` -------------------------------- ### Using NiceMock with EXPECT_CALL Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Demonstrates the basic usage of NiceMock with a specific EXPECT_CALL. Unexpected calls to GetDomainOwner with arguments other than 'google.com' will still result in an error. ```cpp TEST(...) { NiceMock mock_registry; EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) .WillRepeatedly(Return("Larry Page")); // Use mock_registry in code under test. ... &mock_registry ... } ``` -------------------------------- ### UnitTest::skipped_test_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the number of tests that were skipped. ```APIDOC ## UnitTest::skipped_test_count ### Description Gets the number of skipped tests. ### Method `int skipped_test_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The count of skipped tests. ### Response Example N/A ``` -------------------------------- ### Build Google Test and Google Mock Source: https://github.com/google/googletest/blob/main/CONTRIBUTING.md Compile Google Test and/or Google Mock and all enabled tests using the 'make' command on Unix-like systems. ```bash make ``` -------------------------------- ### Build Google Test and Google Mock Tests with CMake Source: https://github.com/google/googletest/blob/main/CONTRIBUTING.md Use this command to set up the build environment for both Google Test and Google Mock, enabling their respective test suites. ```bash mkdir mybuild cd mybuild cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR} ``` -------------------------------- ### UnitTest::test_to_run_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the number of tests that are scheduled to run. ```APIDOC ## UnitTest::test_to_run_count ### Description Gets the number of tests that should run. ### Method `int test_to_run_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The count of tests scheduled to run. ### Response Example N/A ``` -------------------------------- ### UnitTest::disabled_test_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the total number of disabled tests. ```APIDOC ## UnitTest::disabled_test_count ### Description Gets the number of disabled tests. ### Method `int disabled_test_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The count of disabled tests. ### Response Example N/A ``` -------------------------------- ### Basic Mock Usage in a Test Source: https://github.com/google/googletest/blob/main/docs/gmock_cheat_sheet.md Demonstrates the typical workflow for using mocks in a test: include necessary headers, create a mock object, set default actions, define expectations, exercise the code under test, and verify results. Expectations are automatically checked upon mock object destruction. ```cpp using ::testing::Return; TEST(BarTest, DoesThis) { MockFoo foo; ON_CALL(foo, GetSize()) .WillByDefault(Return(1)); // ... other default actions ... EXPECT_CALL(foo, Describe(5)) .Times(3) .WillRepeatedly(Return("Category 5")); // ... other expectations ... EXPECT_EQ(MyProductionFunction(&foo), "good"); } ``` -------------------------------- ### UnitTest::failed_test_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the number of individual tests that have failed. ```APIDOC ## UnitTest::failed_test_count ### Description Gets the number of failed tests. ### Method `int failed_test_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The count of failed tests. ### Response Example N/A ``` -------------------------------- ### UnitTest::successful_test_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the number of individual tests that have passed. ```APIDOC ## UnitTest::successful_test_count ### Description Gets the number of successful tests. ### Method `int successful_test_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The count of successful tests. ### Response Example N/A ``` -------------------------------- ### UnitTest::total_test_suite_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the total number of test suites. ```APIDOC ## UnitTest::total_test_suite_count ### Description Gets the number of all test suites. ### Method `int total_test_suite_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The total count of test suites. ### Response Example N/A ``` -------------------------------- ### UnitTest::failed_test_suite_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the number of test suites that have failed. ```APIDOC ## UnitTest::failed_test_suite_count ### Description Gets the number of failed test suites. ### Method `int failed_test_suite_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The count of failed test suites. ### Response Example N/A ``` -------------------------------- ### Initialize GoogleTest Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Initializes GoogleTest and parses command line flags. Must be called before RUN_ALL_TESTS(). Overloads exist for different argument types and embedded platforms. ```cpp void testing::InitGoogleTest(int* argc, char** argv) void testing::InitGoogleTest(int* argc, wchar_t** argv) void testing::InitGoogleTest() ``` -------------------------------- ### UnitTest::successful_test_suite_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the number of test suites that have passed. ```APIDOC ## UnitTest::successful_test_suite_count ### Description Gets the number of successful test suites. ### Method `int successful_test_suite_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The count of successful test suites. ### Response Example N/A ``` -------------------------------- ### Build and Run GoogleTest with Bazel Source: https://github.com/google/googletest/blob/main/docs/quickstart-bazel.md Compiles and executes the GoogleTest binary using Bazel. The `--cxxopt=-std=c++17` flag ensures C++17 compliance, and `--test_output=all` shows detailed test results. ```bash $ bazel test --cxxopt=-std=c++17 --test_output=all //:hello_test ``` -------------------------------- ### Build and Run Tests with CMake Source: https://github.com/google/googletest/blob/main/docs/quickstart-cmake.md Commands to configure, build, and run your tests using CMake and CTest. This demonstrates the typical workflow for a CMake-based project with GoogleTest. ```bash cmake -S . -B build cmake --build build cd build && ctest ``` -------------------------------- ### UnitTest::reportable_test_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the number of tests that will be included in the XML report. ```APIDOC ## UnitTest::reportable_test_count ### Description Gets the number of tests to be printed in the XML report. ### Method `int reportable_test_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The count of reportable tests. ### Response Example N/A ``` -------------------------------- ### UnitTest::test_suite_to_run_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the number of test suites that are scheduled to run. ```APIDOC ## UnitTest::test_suite_to_run_count ### Description Gets the number of all test suites that contain at least one test that should run. ### Method `int test_suite_to_run_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The count of test suites scheduled to run. ### Response Example N/A ``` -------------------------------- ### UnitTest::current_test_info Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the TestInfo object for the currently running test. ```APIDOC ## UnitTest::current_test_info ### Description Returns the [`TestInfo`](#TestInfo) object for the test that's currently running, or `NULL` if no test is running. ### Method `const TestInfo* current_test_info() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **const TestInfo***: A pointer to the current `TestInfo` object, or `NULL` if no test is running. ### Response Example N/A ``` -------------------------------- ### Deriving Test Fixtures in C++ Source: https://github.com/google/googletest/blob/main/docs/faq.md Demonstrates how to create a base test fixture and derive specialized fixtures from it to share common setup and teardown logic across multiple test suites. Ensure base fixture setup/teardown is called within derived fixture methods. ```c++ // 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 ... ``` -------------------------------- ### Run All Tests Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Runs all registered tests. Returns 0 on success, 1 otherwise. Should be invoked after InitGoogleTest(). ```cpp int RUN_ALL_TESTS() ``` -------------------------------- ### UnitTest::current_test_suite Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the TestSuite object for the currently running test. ```APIDOC ## UnitTest::current_test_suite ### Description Returns the [`TestSuite`](#TestSuite) object for the test that's currently running, or `NULL` if no test is running. ### Method `const TestSuite* current_test_suite() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **const TestSuite***: A pointer to the current `TestSuite` object, or `NULL` if no test is running. ### Response Example N/A ``` -------------------------------- ### Simple Method Mocking (Old vs. New) Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Compares the old MOCK_METHOD1 macro for simple method mocking with its modern MOCK_METHOD equivalent. ```c++ MOCK_METHOD1(Foo, bool(int)) ``` ```c++ MOCK_METHOD(bool, Foo, (int)) ``` -------------------------------- ### UnitTest::elapsed_time Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the total elapsed time of the test run in milliseconds. ```APIDOC ## UnitTest::elapsed_time ### Description Gets the elapsed time, in milliseconds. ### Method `TimeInMillis elapsed_time() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **TimeInMillis**: The elapsed time in milliseconds. ### Response Example N/A ``` -------------------------------- ### Mocking Free Functions via Interface Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Illustrates how to mock free functions by introducing an abstract interface and a concrete subclass that calls the free function. The code then interacts with the interface, allowing for easy mocking. ```cpp class FileInterface { public: ... virtual bool Open(const char* path, const char* mode) = 0; }; class File : public FileInterface { public: ... bool Open(const char* path, const char* mode) override { return OpenFile(path, mode); } }; ``` -------------------------------- ### UnitTest::reportable_disabled_test_count Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the count of disabled tests that will appear in XML reports. ```APIDOC ## UnitTest::reportable_disabled_test_count ### Description Gets the number of disabled tests that will be reported in the XML report. ### Method `int reportable_disabled_test_count() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The count of reportable disabled tests. ### Response Example N/A ``` -------------------------------- ### UnitTest::GetInstance Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the singleton UnitTest object. Constructs it on the first call. ```APIDOC ## UnitTest::GetInstance ### Description Gets the singleton `UnitTest` object. The first time this method is called, a `UnitTest` object is constructed and returned. Consecutive calls will return the same object. ### Method `static UnitTest* GetInstance() ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **UnitTest***: A pointer to the singleton `UnitTest` object. ### Response Example N/A ``` -------------------------------- ### Defining Actions Source: https://github.com/google/googletest/blob/main/docs/reference/actions.md Details how to define custom actions using `ACTION`, `ACTION_P`, and `ACTION_Pk` macros. ```APIDOC ## Defining Actions | Macro | Description | | :--------------------------------- | :-------------------------------------- | | `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | | `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | | `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | The `ACTION*` macros cannot be used inside a function or class. ``` -------------------------------- ### Run Google Test and Google Mock Tests Source: https://github.com/google/googletest/blob/main/CONTRIBUTING.md Execute all compiled tests for Google Test and Google Mock using the 'make test' command. ```bash make test ``` -------------------------------- ### UnitTest::original_working_dir Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Retrieves the working directory at the start of the first test execution. ```APIDOC ## UnitTest::original_working_dir ### Description Returns the working directory when the first [`TEST()`](#TEST) or [`TEST_F()`](#TEST_F) was executed. The `UnitTest` object owns the string. ### Method `const char* original_working_dir() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **const char***: A pointer to a C-style string representing the original working directory. ### Response Example N/A ``` -------------------------------- ### Create GoogleTest as a Shared Library (DLL) Source: https://github.com/google/googletest/blob/main/googletest/README.md Compile GoogleTest as a shared library by defining this flag. This is an alternative to linking it as a static library. ```bash -DGTEST_CREATE_SHARED_LIBRARY=1 ``` -------------------------------- ### Example Usage of HasAbsoluteValue Matcher Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Demonstrates how to use the HasAbsoluteValue matcher in an EXPECT_THAT assertion. ```cpp EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); ``` -------------------------------- ### UnitTest::random_seed Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Retrieves the random seed used at the start of the current test run. ```APIDOC ## UnitTest::random_seed ### Description Returns the random seed used at the start of the current test run. ### Method `int random_seed() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **int**: The random seed value. ### Response Example N/A ``` -------------------------------- ### InitGoogleTest Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Initializes GoogleTest and parses command-line flags. This function must be called before RUN_ALL_TESTS(). Overloads are available for different argument types and embedded platforms. ```APIDOC ## InitGoogleTest ### Description Initializes GoogleTest. This must be called before calling [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it is removed from `argv`, and `*argc` is decremented. Keep in mind that `argv` must terminate with a `NULL` pointer (i.e. `argv[argc]` is `NULL`), which is already the case with the default `argv` passed to `main`. No value is returned. Instead, the GoogleTest flag variables are updated. The `InitGoogleTest(int* argc, wchar_t** argv)` overload can be used in Windows programs compiled in `UNICODE` mode. The argument-less `InitGoogleTest()` overload can be used on Arduino/embedded platforms where there is no `argc`/`argv`. ### Method `void testing::InitGoogleTest(int* argc, char** argv)` `void testing::InitGoogleTest(int* argc, wchar_t** argv)` `void testing::InitGoogleTest()` ``` -------------------------------- ### Type List for Typed Tests Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Example of how to define a list of types for use in type-parameterized tests. ```cpp testing::Types ``` -------------------------------- ### UnitTest::ad_hoc_test_result Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Gets the TestResult for failures or properties logged outside of individual test suites. ```APIDOC ## UnitTest::ad_hoc_test_result ### Description Returns the [`TestResult`](#TestResult) containing information on test failures and properties logged outside of individual test suites. ### Method `const TestResult& ad_hoc_test_result() const ### Endpoint N/A (Class method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **const TestResult&**: A reference to the `TestResult` object for ad-hoc events. ### Response Example N/A ``` -------------------------------- ### GTEST_SKIP Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Prevents further test execution at runtime. It can be used in test cases or setup methods to conditionally skip tests. ```APIDOC ## GTEST_SKIP ### Description Prevents further test execution at runtime. Can be used in individual test cases or in the `SetUp()` methods of test environments or test fixtures (classes derived from the [`Environment`](#Environment) or [`Test`](#Test) classes). If used in a global test environment `SetUp()` method, it skips all tests in the test program. If used in a test fixture `SetUp()` method, it skips all tests in the corresponding test suite. Similar to assertions, `GTEST_SKIP` allows streaming a custom message into it. ### Syntax `GTEST_SKIP()` See [Skipping Test Execution](../advanced.md#skipping-test-execution) for more information. ``` -------------------------------- ### Lambda Action for Mock Function Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Shows how to define a gMock action using a lambda function. The lambda's signature must be compatible with the mocked function. ```cpp MockFunction mock; EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; }); EXPECT_EQ(mock.AsStdFunction()(2), 14); ``` -------------------------------- ### Matcher Overloading with Different Parameter Counts Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Illustrates how to overload matchers with the same name but different numbers of parameters using MATCHER_P and MATCHER_P2. ```cpp MATCHER_P(Blah, a, description_string_1) { ... } MATCHER_P2(Blah, a, b, description_string_2) { ... } ``` -------------------------------- ### TestResult Summary Information Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Get the total count of test parts and the number of test properties associated with a test result. ```cpp int TestResult::total_part_count() const ``` ```cpp int TestResult::test_property_count() const ``` -------------------------------- ### Handling Multiple Call Arguments with EXPECT_CALL Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Shows how to use a wildcard matcher (_) with EXPECT_CALL to catch all other calls to a method, in addition to specific calls. The order of EXPECT_CALLs is important, with newer ones taking precedence. ```cpp EXPECT_CALL(mock_registry, GetDomainOwner(_)) .Times(AnyNumber()); // catches all other calls to this method. EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) .WillRepeatedly(Return("Larry Page")); ``` -------------------------------- ### TestResult Timing and Timestamp Source: https://github.com/google/googletest/blob/main/docs/reference/testing.md Retrieve the elapsed time in milliseconds and the start timestamp in milliseconds since the UNIX epoch for a test. ```cpp TimeInMillis TestResult::elapsed_time() const ``` ```cpp TimeInMillis TestResult::start_timestamp() const ``` -------------------------------- ### Configure CMake for Executable and Testing Source: https://github.com/google/googletest/blob/main/docs/quickstart-cmake.md Add build rules to your CMakeLists.txt to create an executable for your tests, link it against GoogleTest, 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) ``` -------------------------------- ### Define MockTurtle Class with MOCK_METHOD Source: https://github.com/google/googletest/blob/main/docs/gmock_for_dummies.md Demonstrates how to define a mock class 'MockTurtle' by inheriting from the 'Turtle' interface and using the MOCK_METHOD macro to mock its virtual functions. Ensure gMock is included. ```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)); }; ``` -------------------------------- ### Mocking Class Templates with Google Mock Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Demonstrates how to mock class templates by defining a mock class that inherits from the template base class and uses MOCK_METHOD for virtual functions. ```cpp template class StackInterface { ... // Must be virtual as we'll inherit from StackInterface. virtual ~StackInterface(); virtual int GetSize() const = 0; virtual void Push(const Elem& x) = 0; }; template class MockStack : public StackInterface { ... MOCK_METHOD(int, GetSize, (), (const, override)); MOCK_METHOD(void, Push, (const Elem& x), (override)); }; ``` -------------------------------- ### Even Number Cardinality Implementation Source: https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md Example of a custom gMock cardinality that checks if a function was called an even number of times. It implements the CardinalityInterface. ```cpp using ::testing::Cardinality; using ::testing::CardinalityInterface; using ::testing::MakeCardinality; class EvenNumberCardinality : public CardinalityInterface { public: bool IsSatisfiedByCallCount(int call_count) const override { return (call_count % 2) == 0; } bool IsSaturatedByCallCount(int call_count) const override { return false; } void DescribeTo(std::ostream* os) const { *os << "called even number of times"; } }; Cardinality EvenNumber() { return MakeCardinality(new EvenNumberCardinality); } ```