C++ GTest

install GTest with CMake

https://google.github.io/googletest/quickstart-cmake.html

include(FetchContent)
FetchContent_Declare(
        googletest
        URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
enable_testing()

target_link_libraries(
        target_name
        gtest_main gtest
)

first example

#include <gtest/gtest.h>
#include "random"

TEST(test1,t1){
    std::default_random_engine re(std::chrono::system_clock::now().time_since_epoch().count());
    std::uniform_int_distribution<uint8_t>rn(0,10);
    int v1=rn(re),v2=rn(re);
    EXPECT_EQ(v1,v2) << "Vectors x and y are of unequal length";
}
int main(int argc, char *argv[]) {
    testing::InitGoogleTest(&argc,argv);
    return RUN_ALL_TESTS();
}
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from test1
[ RUN      ] test1.t1
[       OK ] test1.t1 (0 ms)
[----------] 1 test from test1 (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[  PASSED  ] 1 test.

EXPECT AND ASSERT

  • ASSERT: Fails fast, aborting the current function.
  • EXPECT: Continues after the failure.

expect throw and death

Test Fixture

class MyTest : public ::testing::Test {

protected:
    void SetUp()override { //done before test like MyTest constructor
        val=12;
    }
    void TearDown()override{//done after test like ~MyTest

    }
    void add(){
        val+=12;
    }
    int val;
};

TEST_F(MyTest, t1) {
    add();
    EXPECT_EQ(val,66)<<string(__FILE__)+":"+string(std::to_string(__LINE__));
}

Disabling and Skipping Tests

Test Filtering

you can run it with parameters to add more options for testing
for filtering, you can add

--gtest_filter=*.f*

Parametrized Test

class LeapYearParameterizedTestFixture :public ::testing::TestWithParam<int> {
protected:
    int val;
};

TEST_P(LeapYearParameterizedTestFixture, OddYearsAreNotLeapYears) {
    val = GetParam();
    ASSERT_EQ(val,12);
}

INSTANTIATE_TEST_CASE_P(
        LeapYearTests,
        LeapYearParameterizedTestFixture,
        ::testing::Values(
                1, 711, 12, 2013
        ));