您好我有一个名为Date
的c ++类。代码如下。如何为班级创建测试运行?对C ++来说非常新。我搜索了很多,但无法找到任何富有成效/有用的网站。请有人可以帮忙吗?提前谢谢。
date.h
#ifndef H_date
#define H_date
#include <iostream>
using namespace std;
class Date{
friend ostream &operator << (ostream & os, const Date &);
friend istream &operator >> (istream & is, Date &);
public:
Date();
Date(int day, int month, int year);
void setday(int day);
void setmonth(int month);
void setyear(int year);
void setDate(int day, int month, int year);
int getday() const;
int getmonth() const;
int getyear() const;
void print() const;
protected:
int day;
int month;
int year;
};
#endif
date.cpp
#include <iostream>
#include "date.h"
using namespace std;
Date::Date()
{
day = 0;
month = 0;
year = 0;
}
Date::Date(int newDay, int newMonth, int newYear)
{
day = newDay;
month = newMonth;
year = newYear;
}
void Date::setday(int newDay)
{
day =newDay;
}
void Date::setmonth(int newMonth)
{
month = newMonth;
}
void Date::setyear(int newYear)
{
year = newYear;
}
void Date::setDate(int newDay, int newMonth, int newYear)
{
day =newDay;
month = newMonth;
year = newYear;
}
int Date::getday()const
{
return day;
}
int Date::getmonth()const
{
return month;
}
int Date::getyear()const
{
return year;
}
void Date::print()const
{
cout << day << ":" << month<< ":" << year <<endl;
}
ostream& operator<< (ostream& osObject, const Date& date1)
{
osObject << date1.day
<< ":" <<date1.month
<< ":" << date1.year;
return osObject;
}
istream& operator>> (istream& isObject, Date& date1)
{
isObject>>date1.day>>date1.month>>date1.year;
return isObject;
}
答案 0 :(得分:0)
对于单元测试,您通常会使用单位测试框架,例如CppUnit:
friend
分类到测试类通常很有用。以下是测试构造函数的示例:
void DateUnitTest::ConstructorTests
{
// Test default-ctor
{
Date date;
CPPUNIT_ASSERT ( date.day == 0 );
CPPUNIT_ASSERT ( date.month == 0 );
CPPUNIT_ASSERT ( date.year == 0 );
}
// Test ctor with args
{
Date date(31,12,2015);
CPPUNIT_ASSERT ( date.day == 31 );
CPPUNIT_ASSERT ( date.month == 12 );
CPPUNIT_ASSERT ( date.year == 2015 );
}
}