需要测试的功能是:
int hire(Payroll * p) throw(out_of_range, logic_error)
{
// error if no holes left
if (staffcount == MAX_EMPLOYEES)
throw (out_of_range("Hire: Too many employees"));
// spin down holes looking for a hole.
for (int i = 0; i < MAX_EMPLOYEES; ++i) {
Payroll *current = staff[i].get(); // get the pointer
if (current == 0) { // it is empty
appay newpay(p); // convert *Payrollto auto_ptr
staff[i] =newpay;
staffcount++; // one more staff
return i; // return index
} else {
// do nothing. Hole is filled
}
}
// should never get here
throw (logic_error("no holes, but count ok")); }
我可以通过抛出out_of_range
错误来测试它,但我想不出任何logic_error
。
以下是out_of_range
主要的测试:
try {
for (int i = 0; i<11; i++){
hr.hire(new Payroll("Prog M. Er", 55757575));
hr.showAllStaff(" after hires");
}
} catch (out_of_range e) {
cout << "Out of range error: " << e.what() << endl;
cout << "DEBUG: carry on processing - line 177 was tested\n";
}
如何为此函数编写logic_error测试的任何帮助将不胜感激! 谢谢。
A
答案 0 :(得分:1)
您一开始并不需要优化。如果省略那么你只需要抛出一个异常,就不会出现逻辑错误而且测试它没有任何问题。更慢,是的,但如果你无论如何都要抛出异常,我怀疑它有什么不同。它还提供了更简单的功能。这是代码:
int hire(Payroll * p) throw (out_of_range)
{
// spin down holes looking for a hole.
for (int i = 0; i < MAX_EMPLOYEES; ++i)
{
Payroll *current = staff[i].get(); // get the pointer
if (current == 0) { // it is empty
appay newpay(p); // convert *Payrollto auto_ptr
staff[i] =newpay;
staffcount++; // one more staff
return i; // return index
} else {
// do nothing. Hole is filled
}
}
// error if no holes left
throw (out_of_range("Hire: Too many employees"));
}
答案 1 :(得分:1)
这可能是一个编程实践不同的领域,但我会提出一个断言,而不是在这里抛出异常。
断言用于表示“应该永远不会发生的事情”;编程错误,可能导致内部数据损坏,或严重违反编写代码的假设。
异常通常用于指示意外或异常的运行时错误(磁盘空间不足,意外的网络错误等)。
如果staffcount
和staff
不同步,则表示编程错误和可能的数据损坏,并且中止程序(具有良好的错误跟踪)可能比继续损坏数据更可取。
C有一个内置的assert
function,但是有替代品可供选择,例如轻量级Boost.Assert(我使用的)和Alexandrescu和Torjo的全功能SMART_ASSERT library。< / p>
答案 2 :(得分:0)
我可以通过两种方式来达到这个例外。
在与staff_count进行比较之后,但在完成执行for循环之前,可能会改变MAX_EMPLOYEES。你必须有另一个线程这样做,并希望它在正确的时间运行。
两个是修改hr.staff数组而不使用hire方法。如果使用MAX_EMPLOYEES Payroll对象填充staff数组,然后调用hire方法,则会遇到该异常。您可能希望朋友类这样做,因为我假设staff数组是私有的。
答案 3 :(得分:0)
这里的问题是你真正需要测试的。我想说你需要测试的是,一旦抛出异常,你的系统的其余部分是否会表现得可接受。鉴于此,您可以暂时将该函数替换为仅抛出异常的函数,确保通过应该捕获它的任何内容正确处理它,然后恢复正确的函数。