单元测试工具 - Gtest【安装篇】

一、工具简介

googletest Google 公司开发一款跨平台( Linux Windows Mac )测试工具。

二、依赖说明

  • Bazel 或者 Cmake :文章采用 cmake 构建,官方推荐 Bazel

  • 支持 C++11 标准的编译器: GNU c++

  • 三、编译安装

    # 下载googletest源码
    cd /tmp
    git clone https://github.com/google/googletest
    # 进入/创建编译目录
    cd googletest
    mkdir build
    cd build
    # 编译 - cmake version<=2.8 可能出现错误,见下文
    cmake ../
    make -j 8
    # 默认安装 
    make install 
    

    执行编译后会得到四个静态库文件:

  • libgtest.a
  • libgtest_main.a
  • libmock.a
  • libmock_main.a
  • 必要的头文件:

  • googltest/include/gtest
  • googlemock/include/gmock
  • 手动安装过程:

  • 拷贝静态库到自定义文件夹
  • 拷贝头文件到自定义文件夹
  • 默认安装(make install):

  • 静态库文件会被拷贝到/usr/local/lib64/
  • 头文件会被拷贝到/usr/local/include/ 说明:根据操作系统安装路径可能不同。
  • 说明:编译后不存在运行时环境(动态库),不需要使用ldconfig加载。

    四、测试程序

    /* file:test.cpp */
    #include <stdio.h>
    #include <gtest/gtest.h>
    int add(int a, int b) {
        return a+b;
    TEST(MyTest, AddTest) {
        EXPECT_EQ(add(1, 2), 3);
    int main(int argc, char *argv[]) {
        ::testing::InitGoogleTest(&argc, argv);
        return RUN_ALL_TESTS();
    
    g++ -o test test.cpp -std=c++11 -lgtest -lgtest_main -lpthread
    
    # ./test 
    [==========] Running 1 test from 1 test suite.
    [----------] Global test environment set-up.
    [----------] 1 test from MyTest
    [ RUN      ] MyTest.AddTest
    [       OK ] MyTest.AddTest (0 ms)
    [----------] 1 test from MyTest (0 ms total)
    [----------] Global test environment tear-down
    [==========] 1 test from 1 test suite ran. (1 ms total)
    [  PASSED  ] 1 test.
    

    五、一些可能的错误和说明

    5.1.cmake版本过低

    cmake版本小于2.8,可能会出现如下参数错误情况:

    CMake Error at googletest/CMakeLists.txt:134 (target_include_directories):
      target_include_directories called with invalid arguments
    CMake Error at googletest/CMakeLists.txt:137 (target_include_directories):
      target_include_directories called with invalid arguments
    CMake Error at googlemock/CMakeLists.txt:110 (target_include_directories):
      target_include_directories called with invalid arguments
    CMake Error at googlemock/CMakeLists.txt:113 (target_include_directories):
      target_include_directories called with invalid arguments