How to catch an Exception with Spock

How to use Spock library

First of all, Spock is a unit-testing library which is usually used with Grails and Groovy. So you have to import the spock dependency in the Build.groovy or Pom.xml:


group: ‘cglib’, name: ‘cglib-nodep’, version: ‘2.2.2’

(* Cglib library, it is necessary for mocking objects)

How to catch Exceptions with Spock

With Spock you can check everything you think, but in this article we are going to focus on Exception and its management.

In addition, you can catch an exception as follows:

In the test code you can see, the external service has been mocked in order to throw a NullPointerException, so our Payment service catch it and it will throw the final ExternalServiceException, as follows:

It is very common, the customer exception thrown has some attributes, for example:

How to check Exception attributes’

Threfore, you would be able to check all of the attributes which the Exception thrown had, as follows:

You can read other interesting articles like Defensive Programming and Resilient Systems. Also you can visit another interesting blogs like Mrhaki’s blog.

Best Regards


Also published on Medium.

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *