Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw/Catch Exception in Groovy

Tags:

groovy

spock

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)
like image 352
Himanshu Yadav Avatar asked Jun 06 '26 09:06

Himanshu Yadav


1 Answers

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.

like image 194
Peter Niederwieser Avatar answered Jun 08 '26 00:06

Peter Niederwieser



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!