2015-10-08 43 views
0

我遇到了Spock規範和異常處理的問題。Spock異常交互失敗,但mockito異常交互的作用?

我有一些代碼調用服務並捕獲某種類型的異常。在catch塊另一類型的異常被拋出:

try { 
    int result = service.invoke(x,y); 
    ... 
} catch (IOException e) { 
    throw BusinessException(e); 
} 

下面的測試案例作品使用的Mockito嘲笑:

given: "a service that fails" 
def service = mock(Service) 
when(service.invoke(any(),any())).thenThrow(new IOException()) 

and: "the class under test using that service" 
def classUnderTest = createClassUnderTest(service) 

when: "the class under test does something" 
classUnderTest.doSomething() 

then: "a business exception is thrown" 
thrown(BusinessException) 

所有測試都通過

但下面的測試案例失敗時使用Spock來處理服務的相互作用:

given: "a service that fails" 
def service = Mock(Service) 
service.invoke(_,_) >> { throw new IOException() } 

and: "the class under test using that service" 
def classUnderTest = createClassUnderTest(service) 

when: "the class under test does something" 
classUnderTest.doSomething() 

then: "a business exception is thrown" 
thrown(BusinessException) 

型BusinessException」的預期異常,但沒有引發異常

我不知道這到底是怎麼回事。它適用於mockito,但不適用於Spock。

我沒有驗證引發異常的服務,所以它不需要在when/then塊中設置。

(使用Groovy全:2.4.5,斯波克芯:1.0 - 常規 - 2.4)

回答

0

下面的示例工作完全正常:

@Grab('org.spockframework:spock-core:1.0-groovy-2.4') 
@Grab('cglib:cglib-nodep:3.1') 

import spock.lang.* 

class Test extends Specification { 

    def "simple test"() { 
     given: 
      def service = Mock(Service) { 
       invoke(_, _) >> { throw new IOException() } 
      } 
      def lol = new Lol() 
      lol.service = service 

     when: 
      lol.lol() 
     then: 
      thrown(BusinessException) 
    } 
} 

class Service { 
    def invoke(a, b) { 
     println "$a $b" 
    } 
} 

class Lol { 
    Service service 

    def lol() { 
     try { 
      service.invoke(1, 2) 
     } catch(IOException e) { 
      throw new BusinessException(e) 
     } 
    } 
} 

class BusinessException extends RuntimeException { 
    BusinessException(Exception e) {} 
} 

也許你已經配置錯誤的東西嗎?

+0

這很奇怪......我恢復了使用Spock交互和代碼現在的作品。搗蛋鬼。將刪除該問題。謝謝回覆。 –

+0

也許這是一個類路徑問題?我寧願把它留在原地,以及我的答案 - 對於未來的提問者。這是一個完整的例子。 – Opal