Tomislav Nakic-Alfirevic
Tomislav Nakic-Alfirevic

Reputation: 10173

How do I declare that I "expect" an exception in a unit test with Groovy, JUnit and Maven?

I have the following Groovy unit test code:

class MyTest extends GroovyTestCase {

    @Test(expected = IllegalArgumentException.class)
    public void testReadFileMissing() {
        // does something which causes an IllegalArgumentException
    }

    // more tests
}

This works perfectly with my Java unit tests, but with groovy tests, mvn clean test runs the test, but the test fails because an IllegalArgumentException was thrown. In other words, my "expected" annotation attribute seems to be completely ignored.

I could of course simply use a try/catch block to check the behaviour I'm interested in, but I'd like to use the JUnit API if possible because that's what it's for and I find the resulting code simpler to read and understand.

So, can anyone tell me what I'm doing wrong?

Upvotes: 0

Views: 691

Answers (2)

dmahapatro
dmahapatro

Reputation: 50245

You can use shouldFail or shouldFailWithCause showcasing exactly which kind of exception is expected from the code under test.

Upvotes: 1

cfrick
cfrick

Reputation: 37033

either don't use GroovyTestCase and the according JUnit class instead as base or go full groovy and use shouldFail. examples are here http://mrhaki.blogspot.de/2009/11/groovy-goodness-testing-for-expected.html

Upvotes: 1

Related Questions