ubuntu使用gtest单元测试框架

gtest是google的开源c++单元测试框架,下面是在ubuntu上的使用步骤。


####安装 gtest development package:

sudo apt-get install libgtest-dev

注意这一步只是安装源代码到/usr/src/gtest,需要用cmake构建Makefile然后再make生成静态库。

1
2
3
4
5
6
sudo apt-get install cmake    #安装cmake
cd /usr/src/gtest
sudo cmake CMakeLists.txt
sudo make

sudo cp *.a /usr/lib/ #拷贝生成的库到/usr/lib/


####写一个简单的测试代码testgcd.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//testgcd.cpp
#include <gtest/gtest.h>

int Gcd(int a, int b) //计算最大公约数
{
return 0 == b ? a : Gcd(b, a % b);
}

TEST(GcdTest, IntTest)
{
EXPECT_EQ(1, Gcd(2, 5));
EXPECT_EQ(2, Gcd(2, 5));
EXPECT_EQ(2, Gcd(2, 4));
EXPECT_EQ(3, Gcd(6, 9));
}

int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

接着用g++编译,注意要链接的库(也可以用cmake构建,这只是个简单的示例):

g++ testgcd.cpp -lgtest_main -lgtest -lpthread

执行下

./a.out

看看输出结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from GcdTest
[ RUN ] GcdTest.IntTest
testgcd.cpp:11: Failure
Value of: Gcd(2, 5)
Actual: 1
Expected: 2
[ FAILED ] GcdTest.IntTest (0 ms)
[----------] 1 test from GcdTest (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] GcdTest.IntTest

1 FAILED TEST

输出结果也比较容易看懂。关于gtest更多文档和使用可以参考官方手册。


####工程下的测试
当测试项目比较多的时候,一般会分离头文件和实现文件,然后可以用cmake构建。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//!gcd.h
#ifndef GCD_H
#define GCD_H
int Gcd(int a, int b);
#endif
//!gcd.cpp
#include "gcd.h"
int Gcd(int a, int b)
{
return 0 == b ? a : Gcd(b, a % b);
}

//!testgcd.cpp
#include "gcd.h"
#include <gtest/gtest.h>

TEST(GcdTest, IntTest)
{
EXPECT_EQ(1, Gcd(2, 5));
EXPECT_EQ(2, Gcd(2, 5));
EXPECT_EQ(2, Gcd(2, 4));
EXPECT_EQ(3, Gcd(6, 9));
}

int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

接下来写一个CMakeLists.txt:(具体信息参考cmake的文档)

1
2
3
4
5
6
cmake_minimum_required(VERSION 2.6)
# Locate GTest
find_package(GTest REQUIRED)include_directories(${GTEST_INCLUDE_DIRS})
# Link testgcd with what we want to test and the GTest and pthread
libraryadd_executable(testgcd testgcd.cpp gcd.cpp)
target_link_libraries(testgcd ${GTEST_LIBRARIES} pthread)

执行:

1
2
3
cmake CMakeLists.txt
make
./testgcd

可以看到相同的执行结果。


#####参考
Google C++ Testing Framework
Getting started with Google Test (GTest) on Ubuntu
A quick introduction to the Google C++ Testing Framework