2014-02-10 74 views
1

我正在計算調用靜態方法的次數。計算Spock中調用靜態方法的次數

我想驗證基本和內部方法調用的計數。

下面顯示的是一個非常簡化的代碼。我嘗試了一些變化,但不能沒有錯誤地運行。

我嘗試驗證的次數:

  • ClassX.CallsClassY()
  • ClassY.DoSomething()

請幫助。

錯誤消息:

Too few invocations for: 

interactions * globalMock.DoSomething() // Does not work (0 invocations) 

Unmatched invocations (ordered by similarity): 

2 * globalMock.DoSomething() 
2 * globalMock.println('Hello Spock') 

    at org.spockframework.mock.runtime.InteractionScope.verifyInteractions(InteractionScope.java:78) 
    at org.spockframework.mock.runtime.MockController.leaveScope(MockController.java:76) 
    at SpockSpec.Count how many times ClassY is called(SpockSpec.groovy:10) 

代碼:

import spock.lang.Specification 

    class SpockSpec extends Specification { 
     def "Count how many times ClassY is called"(){ 
     def count = 5 
     def interactions = count + 1 
     def globalMock = GroovySpy(ClassY, global: true) 

     when: 
     ClassX.CallClassY(count) 

     then: 
     count == 5 
     // TODO: Count how many times ClassY.DoSomething() and ClassX.CallClassY() is called 
     interactions * globalMock.DoSomething() // Does not work 
    } 

    class ClassX { 

     public static void CallClassY(int count) 
     { 
      count.times { 
       ClassY.DoSomething() 
      } 

      ClassY.DoSomething() 
     } 
    } 

    class ClassY { 
     static void DoSomething() { 
      println "Hello Spock" 
     } 
    } 
} 
+1

只有* *全球嘲弄可以模擬靜態方法。有關詳細信息,請參閱參考文檔(http://docs.spockframework.org)。 –

+0

@PeterNiederwieser感謝您的建議。我更新了代碼,並嘗試使用「[Mocking Static Methods](http://docs.spockframework.org/en/latest/interaction_based_testing.html#mocking-static-methods)」部分中定義的GroovySpy,但我仍然得到錯誤。我究竟做錯了什麼? –

+0

有一件事情是錯誤的,嘲笑的方法沒有參數,但'_'的意思是「任何單一的參數」。 –

回答

2

你可以做類似

def "Count how many times ClassB is called"(){ 
     given: 
      def calls = 0 
     and: 
      ClassY.metaClass.'static'.DoSomething = { 
       calls++ 
      } 
     and: 
      def count = 5   
     when: 
      ClassX.CallClassY(count) 
     then: 
      count == calls + 1 
    }