Testing a controller in Grails in easy with the ControllerUnitTestCase
. If we extend our test class from the ControllerUnitTestCase
we get a lot of extra functionality to write our tests. For example the controller is extended with a parameters map so we can set parameter values in our test case. Suppose we the following controller and want to test it:
class SimpleController { def hello = { chain action: 'world', controller: 'other', model: [message: new Expando(text: params.msg)] } }
By extending the ControllerUnitTestCase
the mockController(SimpleController)
method is invoked. This will add (among other things) the map chainArgs
to the controller. The map is filled with the attributes of our chain()
method. And we can use this map in our test to check for correct results:
class SimpleControllerTests extends grails.test.ControllerUnitTestCase { void setUp() { super.setUp() } void testHelloAction() { controller.params.msg = 'Hello world' controller.hello() assertTrue 'world', controller.chainArgs.action assertTrue 'other', controller.chainArgs.controller assertTrue 'Hello world', controller.chainArgs.model.message.text } }