gpt4 book ai didi

unit-testing - 在Spock中调用模拟时是否会创建新的返回对象?

转载 作者:行者123 更新时间:2023-12-02 15:49:44 25 4
gpt4 key购买 nike

当我尝试调用该模拟时,我们注意到它每次都返回一个不同的对象。

List returnedList = []
Service service = Mock()
service.method() >> returnedList

println System.identityHashCode(service.method())
println System.identityHashCode(service.method())
println System.identityHashCode(service.method())

输出:
710903845
1709394654
759720212

有没有办法让它只返回相同的对象?

最佳答案

这是非常有趣的行为。您能否提供服务类代码。
如果方法Service#method()final,则可以解释这种结果

在非最终情况下,测试波纹管为绿色。我正在使用spock 1.0-groovy2.4。

static class Service {
List<String> method() {
return ['a']
}
}

def "mock should return the same object"() {
given:
List returnedList = []
Service service = Mock()
service.method() >> returnedList

when:
def res1 = System.identityHashCode(service.method())
def res2 = System.identityHashCode(service.method())
def res3 = System.identityHashCode(service.method())

then:
service.method().is(returnedList)
res1 == res2
res2 == res3
}

关于unit-testing - 在Spock中调用模拟时是否会创建新的返回对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41491352/

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