google test 入门介绍

来源:互联网 发布:亿慧软件 编辑:程序博客网 时间:2024/05/04 13:21

     在google上下载源代码包解压以后,在linux需要 configure;  make ; make install;  默认会把头文件和库文件放到/usr/local目录下去,你可以在 configure的时候加上  --prefix=target_dir.

   google test把单元测试代码分成三个概念, 第一test,每个断言 assertion都称为test。第二test case,包含一组test(assertion)或者一个test,test case之间也不相互干扰。第三 test program,包含一组或者一个test case。下面的例子会清晰的说明这三者之间的关系。

      1 #include<gtest/gtest.h>
      2 #include<iostream>
      3 using namespace std;
      4
      5
      6
      7 int just_return(int n)
      8 {
      9     if ( 100==n){
     10         return -1;
     11     }
     12
     13     return n;
     14 }
     15
     16 TEST( just_return, input_10_20)//称为 test case
     17 {
     18     EXPECT_EQ( 10, just_return(10));//称为test
     19     EXPECT_EQ( 20, just_return(20));
     20
     21 }
     22
     23 TEST( just_return, input_100)
     24 {
     25     EXPECT_EQ( 100, just_return(100));
     26
     27 }
     28
     29
     30 int main( int argc, char **argv)
     31 {
     32     cout<<"hello gtest"<<endl;
     33     testing::InitGoogleTest(&argc, argv);//必须的初始化
     34
     35
     36     return RUN_ALL_TESTS() ;//会运行所有test case
     37 }
 

   编译时候只要包括include和lib 路径既可以。lib下提供了静态和动态两种lib,编译方法如下

静态库--g++ test.cpp ./lib/libgtest_main.a -I./include/

动态库--g++ test.cpp -I ./include/ -lgtest_main -L./lib/

export LD_LIBRARY_PATH=libgtest_main.so所在的目录。

运行结果如下,failed的项目都会用红色来标识,其余的用绿色。清楚的说明了哪个函数失败,在第几行。

[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from just_return
[ RUN      ] just_return.input_10_20
[       OK ] just_return.input_10_20
[ RUN      ] just_return.input_100
test.cpp:25: Failure
Value of: just_return(100)
  Actual: -1
Expected: 100
[  FAILED  ] just_return.input_100
[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran.
[  PASSED  ] 1 test.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] just_return.input_100

 

    对于那些断言如何使用,请参见google test的帮助文档。

 

原创粉丝点击