CheckException只接受0参数方法; 我如何测试其他方法抛出异常?

han*_*aad 28 delphi unit-testing exception dunit

我想知道在dunit中测试异常的最佳做法是什么.我对Delphi中的方法指针不是很熟悉.是否有可能将参数绑定到方法指针,以便可以在没有参数的情况下调用它.目前我总是写一个额外的方法来手动执行"绑定".如果SUT有很多投掷方法,那将会很烦人.

// What i did before i knew abput CheckExcepion
procedure MyTest.MyMethod_BadInput_Throws;
var
    res: Boolean;
begin
    res := false;
    try
        sut.MyMethod('this is bad');
    except
        on e : MyExpectedException do:
            res := true;
    end;
    CheckTrue(res);
end;

// What i do now
procedure MyTest.MyMethodWithBadInput;
begin
    sut.MyMethod('this is bad');
end;

procedure MyTest.MyMethod_BadInput_Throws;
begin
    CheckException(MyMethodWithBadInput, MyExpectedException);
end;

// this would be nice
procedure MyTest.MyMethod_BadInput_Throws;
begin
    CheckException(
        BindArguments(sut.MyMethod, 'this is bad'),  // <-- how to do this
        MyExpectedException);
end;
Run Code Online (Sandbox Code Playgroud)

Tri*_*enT 44

您可以StartExpectingException用来围绕您的方法调用).

StartExpectingException(MyException);
MyMethod(MyParam);
StopExpectingException();
Run Code Online (Sandbox Code Playgroud)

  • 或者甚至更好,只需在测试中设置ExpectedException属性即可. (4认同)
  • @Jeroen:不,不要试一试......最后.事实上,即使引发异常,也会导致测试失败.`StopExpectingException`实现为:_我不应该被调用; 如果我是,那么一个异常没有被提出,所以测试失败了.把它放在`finally`中只是迫使它失败了测试.严格地说,你根本不需要`StopExpectinException`.如果测试方法在"ExpectedException"状态下正常结束,则测试失败. (4认同)
  • 看到MyMethod会引发一个异常,并且在它执行之后什么都不会发生.如果您有多个支票,则不会执行. (3认同)