TDD

How to test for an exception with Spock

Posted on by  
Hubert Klein Ikkink

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'
    }

}

Continue reading →

shadow-left