使用 gtest 对 C++ 项目进行单元测试

gtest 是谷歌的 C++ 单元测试框架,仓库链接

编译

$ git clone https://github.com/google/googletest.git
$ cd googletest
$ mkdir build && cd ./build
$ cmake .. && make -j4

简单使用

下面测试这样一段代码

// add.h
int add(int a, int b) {
  return a + b;
}

编写测试用例

// test.cc
#include <gtest/gtest.h>
#include "add.h"

TEST(TEST_ADD, demo1) {
    EXPECT_TRUE(add(1, 2) == 3);
    EXPECT_TRUE(add(2, 3) == 5);
}

TEST(TEST_ADD, demo2) {
    EXPECT_TRUE(add(1, 2) == 3);
    EXPECT_TRUE(add(2, 3) == 6);
}

int main(int argc, char* argv[]) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

执行

$ clang++ -I/path/to/googletest/include test.cc -o unit_test -L/path/to/googletest/build/lib -lgtest -lgtest_main -lpthread -std=c++11 && ./unit_test
'''
[==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 2 tests from TEST_ADD
[ RUN      ] TEST_ADD.demo1
[       OK ] TEST_ADD.demo1 (0 ms)
[ RUN      ] TEST_ADD.demo2
test.cc:11: Failure
Value of: add(2, 3) == 6
  Actual: false
Expected: true
[  FAILED  ] TEST_ADD.demo2 (0 ms)
[----------] 2 tests from TEST_ADD (0 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test suite ran. (0 ms total)
[  PASSED  ] 1 test.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] TEST_ADD.demo2

发现 TEST_ADD.demo2 这个用例出错了,因为 2 + 3 != 6,符合预期。