gpt4 book ai didi

unit-testing - 带有 Spock Framework Mock "_"选项的 Groovy Spread Operator

转载 作者:行者123 更新时间:2023-12-04 15:49:39 28 4
gpt4 key购买 nike

我是 groovy 和 Spock 的新手。

我正在尝试创建一个通用方法来模拟我系统中的对象。

问题

我正在尝试创建一个函数,该函数将获取一个对象并动态模拟我想要在该对象中使用的函数。该函数获取带有数据的函数映射,何时模拟它们中的每一个以及返回什么。函数返回错误。

我创建了一个类

    class MetaData {
Object[] argTypes
def returnValue
Object[] argsMatchers

MetaData(Object[] argTypes, returnValue, Object[] argsMatchers) {
this.argTypes = argTypes
this.returnValue = returnValue
this.argsMatchers = argsMatchers
}
}

模拟函数是:

    def mockFunctionTestData(Map overrides = [:], def clazz){
def args = Mock(clazz)
overrides.each { String key, value ->
Object[] argTypes = value.argTypes
if(args.metaClass.respondsTo(args, key, argTypes).size() == 1){
def methodToGetRequest = key
def argsMatchers = value.argsMatchers
def returnValue = value.returnValue

args."$methodToGetRequest"(*argsMatchers) >> returnValue
} else {
println "Error: Trying to add property that doesn't exist"
}
}
return args
}

我正在创建对象:

def functionData = new MetaData([Date, Date, List, boolean] as Object[],
meas,
[_ as Date, _ as Date, new ArrayList<>(), true] as Object[]) //the line that fails
def dogDAO = [getDogData: functionData]


def testDog= mockFunctionTestData(dogDAO , Dog)

上面的代码返回以下异常:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '_' with class 'org.spockframework.lang.Wildcard' to class 'java.util.Date' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.util.Date(org.spockframework.lang.SpreadWildcard)

失败的行

[_ as Date, _ as Date, new ArrayList<>(), true] as Object[]) 

最佳答案

在 Spock 框架中,您无法以这种动态方式创建模拟。 Spock 有自己的编译器(准确地说是 AST 转换),它可以创建可执行的测试代码。只有在交互部分,它才将“_”识别为通配符,将“>>”运算符识别为返回固定值。这就是为什么你得到那个异常(exception)。因为“_”通配符不在交​​互部分。我建议您编写类似于以下内容的测试:

class DogSpec extends Specification {
def "test the dog"() {
when:
def dog = Mock(Dog) {
1 * getDogData(_ as Date, _ as Date, new ArrayList<>(), true) >> "Bark"
}

then:
dog.getDogData(new Date(), new Date(), [], true) == "Bark"
}
}

关于unit-testing - 带有 Spock Framework Mock "_"选项的 Groovy Spread Operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54386547/

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