I am new to groovy and Spock.
I'm trying to create a generic method for mocking objects in my system.
the problem
I'm trying to create a function that will get an object and dynamically mock the functions I want in the object. the function gets a map of functions with data when to mock each of one them and what to return. the functions return an error.
I created a class
class MetaData {
Object[] argTypes
def returnValue
Object[] argsMatchers
MetaData(Object[] argTypes, returnValue, Object[] argsMatchers) {
this.argTypes = argTypes
this.returnValue = returnValue
this.argsMatchers = argsMatchers
}
}
the mocking function is:
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
}
I'm creating the object :
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)
the code above returns the following exception:
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)
the line that fails
[_ as Date, _ as Date, new ArrayList<>(), true] as Object[])