2013-04-09 1316 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