一、工具简介

googletestGoogle公司开发一款跨平台(LinuxWindowsMac)测试工具。

二、依赖说明

  • Bazel或者 Cmake:文章采用cmake构建,官方推荐Bazel
  • 支持C++11标准的编译器:GNUc++

三、编译安装

# 下载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

修改对应文件:google/CMakeLists.txt134137110113行。

修改文件方式:删除target_include_directories函数中SYSTEM参数,如下。

target_include_directories(gtest INTERFACE
Last modification:December 31st, 2019 at 11:04 pm