2

我是 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)
4

2 回答 2

5

而不是test = TestClass(),它应该是test = new TestClass()。要测试预期的异常,请使用Specification.throwntry-catch 代替。有关示例,请参阅 Spock 的Javadoc 。

于 2013-04-09T18:53:58.633 回答
5

这是在 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
于 2013-04-30T10:49:17.697 回答