Search

Dark theme | Light theme

November 18, 2009

Groovy Goodness: Testing for Expected Exceptions

If we create a unit test class and extend from GroovyTestCase we can use the very useful shoulFail() methods. The method provides a very concise way to define that a piece of code should throw an exception. We can specify the type of exception we expect to be thrown or leave it out.

class URLTest extends GroovyTestCase {
    void testNoProtocol() {
        // Test for exception.
        shouldFail {
            def url = new URL('')
        }

        // Test for exception and check resulting message.
        def msg = shouldFail {
            def url =  new URL('')
        }
        assert 'no protocol: ' == msg  // We can use the 'normal' assert.

        // Test for specific exception and resulting message.
        msg = shouldFail(MalformedURLException) {
            def url = new URL('')
        }
        assertEquals 'no protocol: ', msg  // We can use the JUnit assertEquals.
        
        // Test for exception higher up in the hierarchy.
        shouldFail(IOException) {
            def url = new URL('')
        }
    }
}