我很菜鸟,对单元测试一窍不通,下面是我基础的程序:
#include "stdafx.h"
// classes example
#include <iostream>
using namespace std;
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
bool isEq ();
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
bool CRectangle::isEq () {
if(x==y)
{
return true;
}
else
{
return false;
}
}
int main () {
CRectangle rect;
rect.set_values (3,3);
cout << "area: " << rect.area();
cout << " isEq: " << rect.isEq() << " \n";
return 0;
}
我想知道如何测试isEq方法?我希望这个方法的代码覆盖率达到100%,并使用Boost测试框架。有什么想法吗?我正在使用VS 2009 SP1,我需要构建和运行什么?我对单元测试非常困惑。
更新:感谢Stuart,但我仍然不明白我在做什么。我现在有以下代码和以下文件名:
//FILENAME: test.cpp
#include "stdafx.h"
#define BOOST_TEST_MODULE isEq Test
#include <boost/test/included/unit_test.hpp>
#include "CRectangle.h"
BOOST_AUTO_TEST_CASE(isEq_test)
{
CRectangle rect;
rect.set_values(5,5);
BOOST_CHECK_EQUAL(rect.isEq(), true);
rect.set_values(23,9);
BOOST_CHECK_EQUAL(rect.isEq(), false);
}
// FILENAME: CRectangle.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "CRectangle.h"
//#include <boost/test/included/unit_test.hpp>
// classes example
#include <iostream>
using namespace std;
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
bool CRectangle::isEq () {
if(x==y)
{
return true;
}
else
{
return false;
}
}
int main () {
CRectangle rect;
rect.set_values (3,3);
cout << "area: " << rect.area();
cout << " isEq: " << rect.isEq() << " \n";
return 0;
}
//FILENAME: CRectangle.h
//void CRectangle::set_values (int a, int b);
//bool CRectangle::isEq ();
#ifndef CRECTANGLE_H
#define CRECTANGLE_H
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
bool isEq ();
};
#endif
// FILENAME: stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
#ifdef _UT
#define ut_private public
#define ut_protected public
#else
#define ut_private private
#define ut_protected protected
#endif
我想提醒您,我正在使用Visual Studio 2008 SP1(将此项目作为win32控制台应用程序运行)。每当我构建以下文件时,它会给我错误。我也不确定Boost lib应该如何给我测试结果???会打开一个新窗口吗?会发生什么事情?
#include "CRectangle.h"
,就像之前的评论中提到的那样。 - Stuart Golodetz