2013-04-09 1320 views
1

我是Groovy的新手,并试图在我的应用程序中实现Spock框架。 这里是我的测试代码:Groovy中的抛出/捕捉异常

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) 

回答

5

相反的test = TestClass(),它应该是test = new TestClass()。要测试预期的例外情况,请使用Specification.thrown而不是try-catch。以Spock的Javadoc为例。

+0

的Javadoc链接被打破 – switch201 2017-12-04 21:02:09

4

这是处理异常的斯波克正确的方法:

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