Thursday, March 29, 2012

Testing controllers in Grails

In other to unit test controller in Grails you need to extend ControllerUnitTestCase. Also your test class needs to be in same package as the controller class unsed test and the name of your test class needs to be "Tests".

That's it. Now let's see code example.

Simple controller:
class SimpleController {

    def dateService

    def firstAction = {
        render "first"
    }

    def secondAction = {
        render "second"
    }

    def thirdAction = {
        render dateService.currentDateFormated()
    }
}

Service:
class DateService {

    boolean transactional = true

    public String currentDateFormated() {
        return (new Date()).format("MM-dd-yyyy")
    }
}

Unit test for controller.
class SimpleControllerTests extends ControllerUnitTestCase {
    
    protected void setUp() {
        super.setUp()
    }

    protected void tearDown() {
        super.tearDown()
    }

    public void testFirstAction() {
        controller.firstAction()
        assertEquals("first", controller.response.contentAsString)
    }

    public void testSecondAction() {
        controller.secondAction()
        assertEquals("second", controller.response.contentAsString)
    }

    public void testThird() {
        DateService dateService = new DateService()
        controller.dateService = dateService
        controller.thirdAction()
        assertEquals(dateService.currentDateFormated(), controller.response.contentAsString)
    }
}

If your controller references a service you have to explicitly initialise the service from your test like we did testThird() test in SimpleControllerTests tests.