I have a method that throws exception in some cases. My unit test:
class Bob extends GroovyTestCase {
void testClusterInvalidSomeParameter() {
Abc abcClass = new Abc(2, 0)
shouldFail {
abcClass.calculate()
}
}
}
If second parameter == 0, then method throws exception: "Parameter cannot be null". How can I test that it throws exactly this exception?
shouldFail() and shouldFailWithCause() returns the cause/message of the exception. If the message/cause is set then, you can use the assertion as below:
class Bob extends GroovyTestCase {
void testClusterInvalidSomeParameter() {
Abc abcClass = new Abc(2, 0)
String message = shouldFail {
abcClass.calculate()
}
assert message == "Parameter cannot be null"
}
}
A better test would be to also assert the type of Exception thrown:
String message = shouldFail( XyzException ) {
abcClass.calculate()
}
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