Spock Test,只检查方法是否被调用而不执行它

时间:2014-03-27 08:31:23

标签: grails testing spock

在我们的Spock测试中,我们想检查我们的软件中是否选择了正确的路径。但是我们不想测试被调用方法的功能(这是在单独的测试中完成的)

def "Test"() {
    setup:
    service.metaClass.innerMethod = { -> return null }

    when:
    service.doSomething("notexisting@test.com")

    then:
    1 * service.innerMethod(*_)
}

此测试总是失败,因为innerMethod中的代码被调用并且innerMethod中方法调用的调用被计算在内而不是调用方法innerMethod

|  Too few invocations for:
    1 * service.innerMethod(*_)   (0 invocations)

Unmatched invocations (ordered by similarity):

    1 * secondService.doSomething()

我怎样才能获得innerMethod的调用并模拟完整的函数?

1 个答案:

答案 0 :(得分:11)

如果你没有嘲笑服务本身,你需要做这样的事情(注意在使用metaClass时传递适当的参数:

def "Test"() {
    setup:
        def calls = 0
        service.metaClass.innerMethod = { p1 -> calls++ }
    when:
        service.doSomething("notexisting@test.com")
    then:
        calls==1
}

如果你在嘲笑这项服务,

def "Test"() {  
    when:
        service.doSomething("notexisting@test.com")
    then:
        1 * service.innerMethod(_)
}
相关问题