简体   繁体   中英

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?

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

您可以使用shouldFailshouldFailWithCause确切显示被测代码中预期的异常类型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM