gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:48:19 30 4
gpt4 key购买 nike

在我们的 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 并模拟完整的函数?

最佳答案

如果你不模拟服务本身,你需要做这样的事情(注意在使用元类时传递正确的参数:

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(_)
}

关于grails - Spock Test,只检查方法是否被调用,不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22682050/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com