Details
Description
Glen Smith posted a nice mini-tutorial on unit testing controllers here: http://blogs.bytecode.com.au/glen/2008/03/12/mockfor-march---unit-testing-grails-controllers.html. It seems like some of the boilerplate mocking could be taken care of by grails. It would seem to save some repeating one's self when coding unit tests. Graeme suggested the following in the comments:
I think we should have a new ControllerTestCase that has a method like
def withMockController(Class c, Closure c)
that does all of the setting up of params/flash/etc.
Then you could just do
withMockController(LoginController) {
def controller = new LoginController()
lc.login(goodUser)
assertEquals "glen", session.account.userId
assertEquals "/demo/", redirectParams.uri
assertNull flash.loginError
LoginCommand badUser = new LoginCommand(userId: 'glen', password: 'unlucky')
lc.login(badUser)
assertNull session.account
assertNotNull flash.loginError
}
A definite improvement.
I don't want to be too hasty to post up an implementation, but here is my first stab. Attached is the ControllerTestCase, a possible test class that extends ControllerTestCase and the Controller that it is testing.