gpt4 book ai didi

unit-testing - 在 Groovy 中,什么时候使用 Expando 与 'as' 运算符和闭包比较有意义?

转载 作者:行者123 更新时间:2023-12-04 04:43:01 25 4
gpt4 key购买 nike

Groovy 是一种很棒的语言,它提供了许多不同的选择。

在考虑单元测试时,什么时候使用 Expando 有意义对象与带闭包的“as”运算符?

http://groovy.codehaus.org/Developer+Testing+using+Maps+and+Expandos+instead+of+Mocks对比 http://groovy.codehaus.org/Developer+Testing+using+Closures+instead+of+Mocks

对于简单的情况,它们的用法看起来非常相似。

谢谢!

最佳答案

正如您引用的有关使用闭包而不是模拟的页面上所述,它们本身仅适用于模拟接口(interface),并且仅当该接口(interface)具有单一方法时。因此,如果被测类未使用接口(interface),或者您需要模拟多个方法,则需要使用 Expando 或 Map。我更喜欢保持一致并始终使用 Map,我处理的代码很少需要使用单个接口(interface)方法模拟的对象,并且使用 Map 不需要更多的击键。

interface Foo {
def someMethod(s)
}

// Closure, this breaks if someOtherMethod() is added to Foo or if Foo is a class
def mockMethod = { arg -> ...}
def myTestObject = new ObjectUnderTest(mockMetod as Foo)

// Map
def mockMethod = { arg -> ...}
def myTestObject = new ObjectUnderTest([someMethod:mockMethod] as Foo)

不确定使用 Map 或 Expando 来模拟对象之间是否存在显着差异,但我更喜欢 Map 只是因为您可以通过这种方式声明 Map 文字,而不必新建 Expando。

关于unit-testing - 在 Groovy 中,什么时候使用 Expando 与 'as' 运算符和闭包比较有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4709317/

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