如何利用BaseTestCase实现单元测试
虽然BaseTestCase system 是属于主线程的,在执行Test Case 后,BaseTestCase system 将接管主线程的操作权,然后使用BaseTestCase system同样可以完成单元测试,原因很简单,还是因为BaseTestCase system 它是基于代码级的。
下面我们用一个Sample 来演示BaseTestCase system 是如何实现单元测试。
// .h
#ifdef TEST_CASE_CODE
#include "BaseTestCase.h"
class CTest_BitmapFile : public CBaseTestCase
{
TEST_CASE_MAP
BASE_TEST_CASE_H(CTest_BitmapFile)
public:
………..
void test_LoadFile();
………..
};
#endif //#ifdef TEST_CASE_CODE
// .cpp
#ifdef TEST_CASE_CODE
//
// Construction/Destruction
//
BASE_TEST_CASE_CPP(CTest_BitmapFile)
BEGIN_TEST_CASE_MAP(CTest_BitmapFile)
………….
TEST_CASE_MEMBER(test_LoadFile)
………….
END_TEST_CASE_MAP
void CTest_BitmapFile::test_LoadFile()
{
TEST_CASE_TRACE("Begin");
//定义一个将要被测试的对象
CBitmapFile bitMapFle;
// 准备测试数据
TCHAR szApPath [MAX_PATH] = {0};
GetModuleFileName(NULL,szApPath,MAX_PATH);
ASSERT(szApPath);
CString strPath(szApPath);
strPath.Replace("image.exe","sample.bmp");
//记录测试动作,以作为报告输出
TEST_CASE_TRACE("defining a CBitmapFile Object");
TEST_CASE_TRACE("Load File:");
TEST_CASE_TRACE(strPath);
//测试 LoadBitmap 函数
if(TEST_CASE_ASSERT(bitMapFle.LoadBitmap(strPath)))
{
// 检查测试结果是否正确
int nHeight = bitMapFle.GetHeight();
int nWidth = bitMapFle.GetWidth();
// 输出测试结果,以作为报告输出
TEST_CASE_TRACE("Image file info");
char szInfo[MAX_PATH];
wsprintf(szInfo,"Height = %d ,Width = %d ",nHeight,nWidth);
TEST_CASE_TRACE(szInfo);
}
{
// 准备测试环境,一个不存在的文件
strPath.Empty();
//记录测试动作,以作为报告输出
TEST_CASE_TRACE("Test Load a Empty file");
TEST_CASE_ASSERT(bitMapFle.LoadBitmap(strPath));
int nHeight = bitMapFle.GetHeight();
int nWidth = bitMapFle.GetWidth();
char szInfo[MAX_PATH];
wsprintf(szInfo,"Height = %d ,Width = %d ",nHeight,nWidth);
// 因为文件不存在,所以 这个两个变量应该为0 ,使用断言来输出结果
TEST_CASE_ASSERT(((nWidth == 0) || (nHeight == 0)));
// 显示实际的数据,以作为报告输出
TEST_CASE_TRACE(szInfo);
}
TEST_CASE_TRACE("End");
}
#endif //#ifdef TEST_CASE_CODE
从上面可以看到,使用BaseTestCase system 不光可以完成单元测试的动作,同时配合trace 一些信息,可以产出测试报告,真是一举双赢 ^_^