CxxTest的另类使用

CxxTest号称不需要RTTI、成员模板函数、异常处理、及其他外部的库(内存管理、文件/Console IO、图形库等),只需要一个C++编译器,以及Perl或Python之一。因为想将CxxTest的功能嵌入到自己的测试框架中,因此不想使用perl或者python自动生成功能,在64位的ubuntu10.10的系统进行尝试。
实际上按照正常的做法生成一个cpp文件,然后直接编译该文件即可,不需要链接任务外部的库,那么CxxTest必然是把它自己的代码和要测试的代码结合在一起进行编译生成可执行文件。分析生成的cpp文件,他确实是把Root.cpp包含在其中,而Roo.cpp包含了所有CxxTest带的其他cpp文件,也就是它把他自己的所有cpp文件和测试文件一起编译链接的。
第一步:为了避免在文件的文件中包含所有的cpp,我们先把CxxTest编译成一个静态库。
从sourceforge下载了cxxtest-3.10.1.zip,解压到$HOME/cxxtest目录下(为方便,定义一个环境变量:export CXXTEST_DIR=$HOME/cxxtest),那么它所有的.h和.cpp都在$CXXTEST_DIR/cxxtest下面。。
进入$CXXTEST_DIR,创建一个makefile,内容如下:
all:
        g++ -g -c ./cxxtest/Root.cpp -o ./cxxtest/Root.o -I./
        ar rv ./libcxxtest.a ./cxxtest/Root.o
        ranlib ./libcxxtest.a
clean:
        rm -rf ./cxxtest/Root.o ./libcxxtest.a

然后直接make,但此时会报编译错误,诸如:
./cxxtest/Descriptions.cpp:18: error: ‘numberToString’ was not declared in this scope
./cxxtest/LinkedList.cpp:9: error: ‘RealSuiteDescription’ has not been declared
需要对Root.cpp稍作改动,有两种方式:
一是Roo.cpp的#include所有其他.cpp文件之前include一个头文件,即增加一行:
#include <cxxtest/RealDescriptions.h>
二是将Root.cpp中包含RealDescriptions.cpp的那一行移到第一个包含的位置。
无论采用那一种方式,都可成功编译cxxtest,将在$CXXTEST_DIR下生成一个libcxxtest.a的静态库文件。
第二步:创建两个用例来测试:
//MyTestSuite.h
#ifndef MYTESTSUITE_H_
#define MYTESTSUITE_H_
#include "cxxtest/TestSuite.h"
#include "cxxtest/RealDescriptions.h"
#include "cxxtest/ErrorPrinter.h"
class MyTestSuite : public CxxTest::TestSuite {
public:
 void myCase1();
 void myCase2();
};
static class CMyTest1 : public CxxTest::RealTestDescription
{
public:
 CMyTest1();
 void runTest();
} aaa;
static class CMyTest2 :  public CxxTest::RealTestDescription
{
public:
 CMyTest2();
 void runTest();
} bbb;
#endif /* MYTESTSUITE_H_ */

//MyTestSuite.cpp
#include "MyTestSuite.h"
static MyTestSuite mySuite;    //create a suite
static CxxTest::List myList = { NULL, NULL };
CxxTest::StaticSuiteDescription desc( "", 0, "MySuite", mySuite, myList );
CMyTest1::CMyTest1():CxxTest::RealTestDescription( myList, desc, 0, "MyCase1" ) {
}
void CMyTest1::runTest() {
 mySuite.myCase1();
}
CMyTest2::CMyTest2():CxxTest::RealTestDescription( myList, desc, 0, " MyCase2" ) {
}
void CMyTest2::runTest() {
 mySuite.myCase2();
}
void MyTestSuite::myCase1(){
 int x=10*10.00;
 int y=10*9.999;
 TS_ASSERT_EQUALS(x,y);   //failed
}
void MyTestSuite::myCase2(){
 double x=10*10.00;
 double y=10*9.999;
 TS_ASSERT_DELTA(x,y,0.01);  //succeeded
}
int main() {
 return CxxTest::ErrorPrinter().run();
}

编译,链接:
g++ -g -o cxxtest  MyTestSuite.cpp -L$CXXTEST_DIR -lcxxtest  -I$CXXTEST_DIR

程序输出结果:
Running 2 tests
In MySuite::MyCase1:
../MyTestSuite.cpp:27: Error: Expected (x == y), found (100 != 99)
.
Failed 1 of 2 tests
Success rate: 50%

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值