gtest 安装与使用

时间:2024-04-21 04:32:07

打开资源管理器: nautilus .

gtest 获取

从:https://www.bogotobogo.com/cplusplus/google_unit_test_gtest.php

获取gtest-1.7.0-rc1.zip,下载链接,下载打包的源码

或在git仓库下载: git clone https://github.com/google/googletest.git

gtest安装

下载gtest源码包:gtest-1.7.0.zip

解压后进入gtest-1.7.0目录

cmake CMakeLists.txt

make 后生成两个静态库:libgtest.a libgtest_main.a

sudo cp libgtest*.a /usr/lib

sudo cp –a include/gtest /usr/include

测试gtest

下面是进入到sample目录下编译官方提供的用例

cd sample

编译用例1

g++ sample1.cc sample1_unittest.cc -lgtest -lgtest_main -lpthread -o test1

编译用例2

g++ sample2.cc sample2_unittest.cc -lgtest -lgtest_main -lpthread -o test2

由于sample1.cc和sample1_unittest.cc文件中没有编写main函数,这里需要链接libgtest_main.a库,作为程序入口

测试自己的用例

三个源文件

第一个测试函数源文件:SimpleMath.h

// SimpleMath.h

#include <cmath>
double cubic(double d)
{
return pow(d,3);
}

第二个测试用例:TestCase.cpp

#include <gtest/gtest.h>
#include "SimpleMath.h"
TEST(FooTest, RightCase)
{
EXPECT_EQ(8, cubic(2));
}
TEST(FooTest, ErrCase)
{
EXPECT_EQ(27, cubic(3));
}

第三个入口:TestMain.cpp

#include <gtest/gtest.h>
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

编译用的makefile

cc = g++ -std=c++11
prom = test
deps = SimpleMath.h
obj = TestCase.o TestMain.o
LIBS = -lgtest -lpthread $(prom): $(obj)
$(cc) -o $(prom) $(obj) $(LIBS) %.o: %.c $(deps)
$(cc) -c $< -o $@

入门教程

http://www.cnblogs.com/coderzh/archive/2009/03/31/1426758.html