How to test for an exception with Spock

Willem Cheizoo already wrote an blog post about How to test for an exception with JUnit and this inspired me to write the same sample with Spock.

In Spock we can use the thrown() method to check for exceptions. We can use it in a then: block of our test.

This test just reads like a sentence: When the service.publishArticle method is invoked with argument null, then an ArticleNotFoundException is thrown. The message in the exception is ‘Article not found please provide an article to publish’. Nice!

To test if an exception is not thrown we can use the notThrown() method:

With the following implementation of the JDrivenService we run our specification:

This entry was posted in Groovy, TDD and tagged , by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

2 thoughts on “How to test for an exception with Spock

Leave a Reply

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