计算在Spock中调用静态方法的次数

时间:2014-02-10 17:25:54

标签: unit-testing groovy 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 个答案:

答案 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
    }
相关问题