Himanshu Yadav
Himanshu Yadav

Reputation: 13585

Throw/Catch Exception in Groovy

I am new to Groovy and trying to implement Spock framework in my application. Here is my test code:

def "Test class with mock object"()  {

        setup:
        SomeObject sp = Mock()
        test= TestClass()

        when:
        System.out.println('comes here');
        push.exec(sp)

        then:
        sp.length == 1

    }

Here TestClass is throwing some exception which I have to catch in test method or throw it again. I tried

try {

  push.exec(sp)
} catch (Exception e) {

}

But still getting

groovy.lang.MissingMethodException: No signature of method: test.spock.TestClassTest.TestClass() is applicable for argument types: () values: []
Possible solutions: use([Ljava.lang.Object;), use(java.util.List, groovy.lang.Closure), use(java.lang.Class, groovy.lang.Closure), dump(), with(groovy.lang.Closure), each(groovy.lang.Closure)

Upvotes: 2

Views: 8539

Answers (2)

Kamil Roman
Kamil Roman

Reputation: 1071

That's the correct way to handle exceptions in Spock:

def "Test class with mock object"()  {

    setup:
    SomeObject sp = Mock()
    test= TestClass()

    when:
    System.out.println('comes here');
    push.exec(sp)

    then:
    thrown(YourExceptionClass)
    sp.length == 1

}

or if you want to check some data in your exception you may use something like:

    then:
    YourExceptionClass e = thrown()
    e.cause == null

Upvotes: 5

Peter Niederwieser
Peter Niederwieser

Reputation: 123910

Instead of test = TestClass(), it should be test = new TestClass(). To test for an expected exception, use Specification.thrown instead of try-catch. See Spock's Javadoc for an example.

Upvotes: 5

Related Questions