Reputation: 817
I'm trying to unit test a service method that takes as parameters a date and the params LinkedHashMap from the controller. The setup is as follows:
def save = {CustomCommandObject erc ->
...
if (erc.conditionProperty != null) {
def result = myService.ServiceMethod(someDate, params)
...
}
....
redirect(controller: 'controllerName', action: 'actionName', id: params.id)
}
class MyService {
static transactional = false
....
def TypeToReturn ServiceMethod(Date someDate, def params){
...
TypeToReturn typeToReturn = new TypeToReturn(params)
return typeToReturn
}
....
}
One of the tags on the GSP view is of type < joda:timerPicker >:
and TypeToReturn has a property:
LocalTime propertyName
When the application runs normally in the browser the params map is passed correctly to the service method and new TypeToReturn(params) creates an instance of TypeToReturn. params contains the following:
{java.util.LinkedHashMap$Entry@xxxxx} propertyName_hour -> 20
{java.util.LinkedHashMap$Entry@xxxxx} propertyName_minute -> 30
{java.util.LinkedHashMap$Entry@xxxxx} propertyName -> struct
Therefore, in my test for the service method i have the following:
void testSomething() {
LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
params.put("propertyName","struct")
params.put("propertyName_hour", "20")
params.put("propertyName_minutes", "30")
myService = new MyService()
Date d = new Date()
myService.ServiceMethod(d,params)
}
However when i try and run the test i get the following error:
org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object 'struct' with class 'java.lang.String' to class
'org.joda.time.LocalTime'
If i ommit params.put("propertyName","struct") from the map completely then again it (correctly) errors saying that TypeToReturn does not have a property propertyName_hour
How therefore, should I be unit testing such a service method that uses the params Map from the controller? Simply recreateing the map in the test doesn't seem to work. Should the params Map be mocked/stubbed in a partiular way?
Thanks
Upvotes: 2
Views: 2771
Reputation: 5321
Are you running your test as a unit or integration test? If it's not already there, try moving it into test/integration and run it from there using
grails test-app integration:
That runs the test within the Grails environment and will give the joda-time plugin the opportunity to do whatever meta programming magic it's doing to create the type conversion to DateTime it looks like you're missing.
Upvotes: 1