Groovy中的抛出/捕获异常

Groovy中的抛出/捕获异常,groovy,spock,Groovy,Spock,我是Groovy新手,尝试在我的应用程序中实现Spock框架。 以下是我的测试代码: def "Test class with mock object"() { setup: SomeObject sp = Mock() test= TestClass() when: System.out.println('comes here'); push.exec(sp) then:

我是Groovy新手,尝试在我的应用程序中实现Spock框架。 以下是我的测试代码:

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

    }
这里
TestClass
抛出了一些异常,我必须在测试方法中捕获这些异常,或者再次抛出它。我试过了

try {

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

}
但还是越来越

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)

它应该是
test=newtestclass()
,而不是
test=TestClass()
。要测试预期的异常,请使用
Specification.thround
而不是try-catch。请参阅Spock’s以获取示例。

这是处理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

}
或者,如果要检查异常中的某些数据,可以使用以下方法:

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

Javadoc链接已断开