在Ubuntu12.04上使用gtest

来源:互联网 发布:绿色建筑设计评价软件 编辑:程序博客网 时间:2024/05/16 10:51

Google test是Google开发的编写C/C++代码单元测试的框架。

在本文中描述了如何在Ubuntu上使用gtest.

首先需要下载gtest的安装包:

sudo apt-get install libgtest-dev

在安装完成之后,此包里面只包含一些源代码,库文件需要自己进行编译。
sudo apt-get install cmake # install cmakecd /usr/src/gtestsudo cmake CMakeLists.txtsudo make # copy or symlink libgtest.a and libgtest_main.a to your /usr/lib foldersudo cp *.a /usr/lib

假如我们要测试一个函数如下:

// whattotest.cpp#include <math.h> double squareRoot(const double a) {    double b = sqrt(a);    if(b != b) { // nan check        return -1.0;    }else{        return sqrt(a);    }}

然后我们编写此函数的单元测试文件:

// tests.cpp#include "whattotest.cpp"#include <gtest/gtest.h> TEST(SquareRootTest, PositiveNos) {     ASSERT_EQ(6, squareRoot(36.0));    ASSERT_EQ(18.0, squareRoot(324.0));    ASSERT_EQ(25.4, squareRoot(645.16));    ASSERT_EQ(0, squareRoot(0.0));} TEST(SquareRootTest, NegativeNos) {    ASSERT_EQ(-1.0, squareRoot(-15.0));    ASSERT_EQ(-1.0, squareRoot(-0.2));} int main(int argc, char **argv) {    testing::InitGoogleTest(&argc, argv);    return RUN_ALL_TESTS();}

然后使用g++进行编译:

g++ -o tests test.cpp -lgtest -lpthread

运行./tests可以得到如下结果:

[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from SquareRootTest
[ RUN      ] SquareRootTest.PositiveNos
[       OK ] SquareRootTest.PositiveNos (0 ms)
[ RUN      ] SquareRootTest.NegativeNos
[       OK ] SquareRootTest.NegativeNos (0 ms)
[----------] 2 tests from SquareRootTest (0 ms total)


[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran. (0 ms total)
[  PASSED  ] 2 tests.

0 0
原创粉丝点击