google开源测试框架的使用(一)[转]

原文地址

关键字: cmake Hadoop WebSphere Studio BIRT WebStart

下面对这个测试框架在linux平台下的安装和使用做一个简单的介绍。

  google开放了一个测试框架,可以用于测试多种平台下的C++代码。该开源项目的主页是http://code.google.com/p/googletest/ 。

  下面对这个测试框架在linux平台下的安装和使用做一个简单的介绍。

  1. 获得源代码进行安装

   项目的源代码可以从http://code.google.com/p/googletest/downloads/list获得(昨天下载源码的时候最新版本还是1.0.0,现在最新版就变成了1.0.1,加入了对 Visual Studio 7.1 的支持)。获得源码后进行configure make make install,不再多说。

   安后会多出了三个命令,分别是 gtest-config gtester gtester-report。其中gtest-config用于生成编译和连接时的参数,gtester是运行测试程序的命令,gtester-report用于将gtester声称的日志文件转换为html格式。

   下面将通过一个小程序的测试来说明这个测试工具的使用方法

  2. 需要进行测试的代码

   这里列出进行测试的代码,一共两个文件 code.h code.cpp 。

  code.h
   #ifndef CODE_H
   #define CODE_H
   int f( int a );
   int b( int b );
   #endif
  code.cpp
   #include "code.h"
   int f( int a ){
     return a+1;
   }
   int b( int b ){
     return b+2;
   }

  3. 编写测试代码

  测试代码为code_test.cpp

   #include <limits.h>
   #include "code.h"
   #include <gtest/gtest.h>
   TEST( TEST_A,NAME ){     //TEST_A 是测试用例名称, NAME 是测试名称
     EXPECT_EQ( 2,f( 1 ) );  //这个测试执行函数f,参数为1,查看返回值是不是2
     EXPECT_EQ( 3,f( 2 ) );
   }
   TEST( TEST_B,NAME ){
    EXPECT_EQ( 10,b( 2 ) );
   }

  4. 运行测试代码

   运行测试代码需要一个主函数,在这里主函数在文件 main_test.cpp 中

  main_test.cpp
  #include <gtest/gtest.h>
  #include <iostream>
  int main(int argc, char **argv) {
    // std::cout << "Running main() from gtest_main.ccn";
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
  }

  5. 编译

   使用下面的命令进行编译和连接

  gcc $(gtest-config --cppflags --cxxflags) -o code.o -c code.cpp
  gcc $(gtest-config --cppflags --cxxflags) -o code_test.o -c code_test.cpp
  gcc $(gtest-config --cppflags --cxxflags) -o main_test.o -c main_test.cpp
  gcc $(gtest-config --ldflags --libs) -o main_test code.o code_test.o main_test.o

  6. 测试

   使用gtester运行上面编译的程序

$ gtester -o test.log -k main_test
TEST: main... [==========] Running 2 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 1 test from TEST_A
[ RUN   ] TEST_A.NAME
[    OK ] TEST_A.NAME
[----------] 1 test from TEST_B
[ RUN   ] TEST_B.NAME
code_test.cpp:13: Failure
Value of: b( 2 )
Actual: 4
Expected: 10
[ FAILED ] TEST_B.NAME
[----------] Global test environment tear-down
[==========] 2 tests from 2 test cases ran.
[ PASSED ] 1 test.
[ FAILED ] 1 test, listed below:
[ FAILED ] TEST_B.NAME
1 FAILED TEST
(pid=9128)
FAIL: main

  这里可以看到测试用例的通过情况

posted on 2010-01-03 11:48  nwf  阅读(472)  评论(0编辑  收藏  举报

导航