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.
import spock.lang.*
public class JDrivenServiceSpecification extends Specification {
private JDrivenService service = new JDrivenService()
def "publishArticle throws ArticleNotFoundException() {
when:
service.publishArticle null
then:
final ArticleNotFoundException exception = thrown()
// Alternate syntax: def exception = thrown(ArticleNotFoundException)
exception.message == 'Article not found please provide an article to publish'
}
}
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:
import spock.lang.*
public class JDrivenServiceSpecification extends Specification {
private JDrivenService service = new JDrivenService()
def "publishArticle throws ArticleNotFoundException() {
when:
service.publishArticle 'valid'
then:
final ArticleNotFoundException exception = notThrown()
// Alternate syntax: def exception = notThrown(ArticleNotFoundException)
}
}
With the following implementation of the JDrivenService
we run our specification:
class JDrivenService {
String article
void publishArticle(final String article) throws ArticleNotFoundException {
if (!article) throw new ArticleNotFoundException('Article not found please provide an article to publish')
this.article = article
}
}
class ArticleNotFoundException extends Exception {
ArticleNotFoundException(String message) {
super(message)
}
}