Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy GroovyTestCase shouldFail exception message

I have a method that throws exception in some cases. My unit test:

class Bob extends GroovyTestCase {

    void testClusterInvalidSomeParameter() {
        Abc abcClass = new Abc(2, 0)
        shouldFail {
            abcClass.calculate()
        }
    }
}

If second parameter == 0, then method throws exception: "Parameter cannot be null". How can I test that it throws exactly this exception?

like image 257
Bob Avatar asked Oct 21 '25 04:10

Bob


1 Answers

shouldFail() and shouldFailWithCause() returns the cause/message of the exception. If the message/cause is set then, you can use the assertion as below:

class Bob extends GroovyTestCase {

    void testClusterInvalidSomeParameter() {
        Abc abcClass = new Abc(2, 0)

        String message = shouldFail {
            abcClass.calculate()
        }

        assert message == "Parameter cannot be null"
    }
}

A better test would be to also assert the type of Exception thrown:

String message = shouldFail( XyzException ) {
    abcClass.calculate()
}
like image 151
dmahapatro Avatar answered Oct 23 '25 16:10

dmahapatro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!