The dynamic methods added by the Grails framework are not available in unit tests, unless you mock them, however, you can use the testing plug-in to do this for you. As of Grails 1.1 the testing plug-in is one of the core plug-ins, so there is no need to install it.
Here's a cut down example from Chapter 6 of my book, assume we have a MessageController that binds the 'title' and 'detail' parameters from a request onto a Message domain class. We could test this controller called the save method on the domain class like so:
Here we have asked the Grails testing plug-in to mock the Message domain class and controller. By mocking the domain class the unit test adds the GORM methods on, like save, list, get etc. and uses the list we have supplied savedMessages to temporarily store any messages that are saved. In this way we are able to assert that the message has actually been saved in the controller.
thanks for introducing these mock methods. That's a cool concept.
But i'm sorry to say that i have a Exception in my code that matches line 16 in your last code block
groovy.lang.MissingPropertyException: No such property: params for class: TaskController
My TaskController (that corresponds to your MessageController) has actually no property at all, except
def scaffold = Task
Am i missing something in the controller?
Joined: Feb 24, 2009
That's interesting. I have to say that I have never tested a scaffolded controller before as I haven't written any logic to require testing.
I have just quickly spiked what I think you are trying and it does fail but I get a different issue, namely the action closure does not exist. Now I am not entirely surprised by that, but I am able to set the behaviour on the params object.
Here's what I have, hope that helps:
I am using Grails 1.1, rather than 1.0 with the testing plug-in.
Joined: Mar 21, 2003
i had the Task and not the TaskController in the mockController method
Now it fails at the same line.
I think i'll wait with testing until i'am beyond scaffolding and then your sample will be very helpful.