1. 判断是否安装cmake
打开终端,输入cmake -v
,如果没有安装,输入sudo apt-get install cmake
。
2. 下载googletest
打开终端输入:git clone https://github.com/google/googletest.git
3. 编译安装
# 进入下载的googletest目录
cd ~/Downloads/googletest-master
# 创建文件夹mydir,用于作为cmake的目录
mkdir build
# 进入build目录
cd build
# 输入cmake $(GTEST_DIR)进行编译,${GTEST_DIR}为下载的GoogleTest的目录
cmake ../googletest
# 安装
make
4. 测试
(1)新建一个文件夹用于存放测试代码
cd ~/Downloads
mkdir gtest_test
(2)建立三个文件,内容如下:
a. sample.h
#ifndef C_SAMPLES_SAMPLE_H_
#define C_SAMPLES_SAMPLE_H_
int Add(int value1, int value2);
#endif // C_SAMPLES_SAMPLE_H_
b. sample.cpp
#include "sample.h"
int Add(int value1, int value2) {
return (value1 + value2);
}
c. test.cpp
#include <gtest/gtest.h>
#include "sample.cpp"
TEST(Add, case1) {
EXPECT_LT(-2, Add(1, 2));
EXPECT_EQ(-1, Add(1, 2));
ASSERT_LT(-2, Add(1, 2));
ASSERT_EQ(-1, Add(1, 2));
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
(3)编译:
g++ -std=c++11 test.cpp -o test -lgtest -lpthread
# 或者 g++ -std=c++11 test.cpp -o main /usr/local/lib/libgtest.a -lpthread
其中 libgtest.a -lpthread是动态链接库。
注意:一定要添加“-std=c++11”这个参数,否则会报错
“error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
#error This file requires compiler and library support \”。
(4)执行生成的test文件
./test
(5)结果如下: