Bob
Bob

Reputation: 10815

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?

Upvotes: 4

Views: 4378

Answers (1)

dmahapatro
dmahapatro

Reputation: 50285

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()
}

Upvotes: 7

Related Questions