Throw/Catch Exception in Groovy

做~自己de王妃 提交于 2020-01-05 03:39:17

问题


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)

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/15909716/throw-catch-exception-in-groovy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!