您的位置:首页 > 编程语言 > C语言/C++

一个简单地C++ Unit Test framework

2010-12-26 12:24 453 查看

一 使用

先说一下如何使用这个framework。其基本用法和java的junit差不多,只是没那么强大而已。看一下下面所示的这个IntWraper 类:

定义一个测试类,在这个类中使用下列宏来申明test case:

DECLARE_AS_TESTER                //申明一个类为tester,需要放在开头[必有]

DECLARE_SETUP                        //申明一个setup方法[可选]

DECLARE_TEARDOWN                //申明一个teardown方法用于清理工作[可选]

DECLARE_TEST(testName)          //申明一个test[至少有一个,否则没意义]

3.  实现定义的setup,teardown,和test方法;

4.  调用宏CALL_TEST注册这个unit test:

5.  在主程序中定义一个TestMain,然后调用它的run方法:

using namespace FTest;

TestMain myTest(std::cout);

myTest.run();

对IntWraper的完整的test 代码如下:

代码

[code]/*!
* Copyright (c) 2010 FengGe(CN), Inc
* All rights reserved
* This program is UNPUBLISHED PROPRIETARY property of FengGe(CN).
* Only for internal distribution.
*
* @file: FAssert.h
*
* @brief: used for my test framework
*
* @author: li_shugan@126.com
*
* @version: 1.0
*
* @date: 2010-12-25
*/
#ifndef _FASSERT_H
#define _FASSERT_H
#include <ostream>
#include <string>
#include <sstream>
#include "FTest.h"

namespace FTest
{
using std::ostream;
using std::endl;
using std::string;
using std::stringstream;

class TestMain
{
public:
TestMain(ostream& rOstream):
m_pStream(&rOstream)
,m_nFailedCnt(0)
,m_nSuccCnt(0)
{
g_pInstance = this;
}

~TestMain( )
{
getSteam()<<"Total: "<<m_nFailedCnt + m_nSuccCnt << " Success: "<<m_nSuccCnt<<" Failed: "<<m_nFailedCnt<<endl;
g_pInstance  = NULL;
}

void run()
{
TestSuite::getRootSuite()->run();
}

public:
static ostream& getSteam(){return *(g_pInstance->m_pStream);}
static void addFaildCnt() {++g_pInstance->m_nFailedCnt;}
static void addSuccCnt() {++g_pInstance->m_nSuccCnt;}

private:
ostream*    m_pStream;
int         m_nFailedCnt;
int         m_nSuccCnt;
static TestMain* g_pInstance;
};

TestMain* TestMain::g_pInstance = NULL;

inline void Assert(bool bTrue,const string& strFile,int nLine)
{
if (!bTrue)
{
TestMain::getSteam()<<"Failed at "<<strFile<<"("<<nLine<<")"<<endl;
TestMain::addFaildCnt();
}
else
{
TestMain::addSuccCnt();
}
}

template <typename T1,typename T2>
void AssertEqual(const T1& lhs,const T2& rhs,const string& strFile,int nLine)
{
if (lhs != rhs)
{
TestMain::getSteam()<<"Failed at "<<strFile<<nLine<<": expected "<<lhs<<" but "<<rhs<<endl;
TestMain::addFaildCnt();
}
else
{
TestMain::addSuccCnt();
}
}
}

#define ASSERT(b)   FTest::Assert(b,__FUNCTION__,__LINE__)
#define ASSERTFAIL(b) FTest::Assert(!b,__FUNCTION__,__LINE__)
#define ASSERTEQUAL(lhs,rhs) FTest::AssertEqual(lhs,rhs,__FUNCTION__,__LINE__)

#endif //FASSERT_H
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: