Testing for Exceptions

Let’s now look at writing exception tests. We could wrap the method in try-catch. If the method throws the expected exception—that is, if we land in the catch block—all is well.

If the code does not throw any exceptions, we’ll invoke fail to indicate the failure of the test, as shown here:

UnitTestingWithGroovy/ExpectException.groovy
 
try​ {
 
divide(2, 0)
 
fail ​"Expected ArithmeticException ..."
 
} ​catch​(ArithmeticException ex) {
 
assertTrue true ​// Success
 
}

The previous code is Java-style JUnit testing and works with Groovy, as well. However, Groovy makes it easier to write exception tests by providing a method shouldFail that elegantly wraps up the boilerplate code. Let’s use that to write an exception ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.