单元测试利器 - Gtest【安装】

单元测试工具 - Gtest

目前就个人来说,单元测试工具(c/c++)用的比较多的是google的开源测试框架gtest

因为其有较好的输出格式,打桩功能等,尽管有许多不足(读者自行挖掘吧),但是没办法啊,测试框架已经找不到更好的了。

安装需要

Bazel或者 Cmake:笔者这里采用社区支持的cmake构架,官方推荐Bazel,毕竟是google自家的东东。

支持C++11标准的编译器:Unix一般自带的c++编译器都应该支持了吧。

安装

# 下载googletest源码
cd /tmp
git clone https://github.com/google/googletest
# 进入/创建编译目录
cd googletest
mkdir build
cd build
# 编译 - 版本2.8.11可能出现错误
cmake ../
make -j 8
# 自动脚本安装 - sudo权限(也可以手动安装)
make install 

执行编译后会得到四个静态库:libgtest.alibgtest_main.alibmock.alibmock_main.a

头文件路径:googltest/include/gtestgooglemock/include/gmock

手动安装过程:拷贝上述四个静态库到自定义文件夹,拷贝头文件到自定义文件夹。

默认安装:上述静态库文件被拷贝到/usr/local/lib64,头文件被拷贝到/usr/local/

编译测试

// 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.

一些可能的错误

这里我使用的cmake版本为2.8.11,会出现参数错误情况:

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.txt中第134行的target_include_directories函数中SYSTEM参数删除,对上述错误同理):

target_include_directories(gtest INTERFACE
Last modification:October 23rd, 2019 at 02:00 pm
Buy Me A Coffee

Leave a Comment