Testing Controllers

Unit & Integration Testing Controllers

Unit Testing

TODO

Integration Testing

To test controllers with all the dynamic methods already injected you have to understand the Spring Mock Library

Essentially Grails automatically configures each test with a MockHttpServletRequest, *Response, *Session which you can then use to perform your tests. For example consider the following controller:

class FooController {

	def text = {
	    render "bar"
	}

	def someRedirect = {
		redirect(action:"bar")
	}
}

The tests for this would be:

class FooControllerTests extends GroovyTestCase {

  void testText() {
		def fc = new FooController()
		fc.text()
		assertEquals "bar", fc.response.contentAsString
	}

	void testSomeRedirect() {

		def fc = new FooController()
		fc.someRedirect()
		assertEquals "/foo/bar", fc.response.redirectedUrl
	}
}

In the above case the response is an instance of MockHttpServletResponse which we can use to obtain the contentAsString (when writing to the response) or the URL redirected to for example.

Integration Tests for Controllers with Services

If your controller references a service, you have to explicitly initialise the service from your test. e.g.

class FilmStarsController {
    def popularityService
    
    def update = {
        // do something with popularityService
    }

}

In your test you need to set the service as below

class FilmStarsTests extends GroovyTestCase {
      def popularityService

  public void testInjectedServiceInController ()
  {
      def fsc = new FilmStarsController()
      fsc.popularityService = popularityService
      fsc.update()
  }
}

Labels

 
(None)