我正在使用DUnitX框架,我正在尝试测试该过程是否抛出异常.
目前我有以下测试程序:
procedure TAlarmDataTest.TestIdThrowsExceptionUnderFlow;
begin
Input := 0;
Assert.WillRaise(Data.GetId(input), IdIsZeroException, 'ID uninitialized');
end;
Run Code Online (Sandbox Code Playgroud)
当我去编译时,我得到一个错误'没有可以使用这些参数调用的'WillRaise'的重载版本.
有没有更好的方法来检查过程是否引发自定义异常,或者我应该使用try,除非捕获异常时传递的块除外?
第一个参数WillRaise是TTestLocalMethod.这被宣布为:
type
TTestLocalMethod = reference to procedure;
Run Code Online (Sandbox Code Playgroud)
换句话说,您打算传递一个WillRaise可以调用的过程.你不是那样做的.你正在调用这个程序.像这样做:
Assert.WillRaise(
procedure begin Data.GetId(input); end,
IdIsZeroException,
'ID uninitialized'
);
Run Code Online (Sandbox Code Playgroud)
关键是WillRaise需要调用预期会引发的代码.如果调用代码,则会在准备要传递的参数时引发异常WillRaise.因此,我们需要推迟执行预期会增加的代码,直到我们进入内部WillRaise.将代码包装在匿名方法中是实现此目的的一种简单方法.
对于它的价值,实现WillRaise看起来像这样:
class procedure Assert.WillRaise(const AMethod : TTestLocalMethod;
const exceptionClass : ExceptClass; const msg : string);
begin
try
AMethod;
except
on E: Exception do
begin
CheckExceptionClass(e, exceptionClass);
Exit;
end;
end;
Fail('Method did not throw any exceptions.' + AddLineBreak(msg),
ReturnAddress);
end;
Run Code Online (Sandbox Code Playgroud)
因此,WillRaise在try/except块中包含对过程的调用,如果未引发所需的异常,则会失败.
如果你仍然在努力理解这一点,那么我怀疑你需要提高你对匿名方法的了解.一旦掌握了这一点,我相信它会很明显.