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;
In order to test the exception thrown by any method in JUnit 4, you need to use @Test(expected=IllegalArgumentException. class) annotation. You can replace IllegalArgumentException. class with any other exception e.g. NullPointerException.
There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.
If you want to test a scenario in which an exception should be thrown then you should use the expected annotation. If you want to test a scenario where your code fails and you want to see if the error is correctly handled: use expected and perhaps use asserts to determine if it's been resolved.
When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
You can use StartExpectingException
to surround your your method call).
StartExpectingException(MyException); MyMethod(MyParam); StopExpectingException();
I don't know if DUnit supports it yet, but this is a perfect use case for anonymous methods which were introduced in Delphi 2010. If DUnit doesn't support it then you can easily modify the source yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With