Search code examples
delphiunit-testingexceptiondunit

CheckException only accepts 0-parameter methods; how do I test that other methods throw exceptions?


I'm wondering what's the best practice to test for exceptions in dunit. I am not very familiar with method pointers in Delphi. Is there any possibility to bind arguments to a method pointer so that it could be invoked without arguments. At the moment I always write an additional method which does this 'binding' manually. This is going to be annoying if the SUT has a lot of throwing methods.

// 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;

Solution

  • You can use StartExpectingException to surround your your method call).

    StartExpectingException(MyException);
    MyMethod(MyParam);
    StopExpectingException();