Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing a controller method?

I have a controller method like such:

def search = {
    def query = params.query

            ...

    render results as JSON
}

How do I unit test this? Specifically, how do I call search to set params.query, and how do I test the results of the method render? Is there a way to mock the render method, perhaps?

like image 227
Stefan Kendall Avatar asked May 17 '10 01:05

Stefan Kendall


1 Answers

Subclass grails.test.ControllerUnitTestCase for your unit tests. Grails will automatically instantiate your controller and mock out versions of render and redirect that allow you to test the results easily. Just assign the test inputs to controller.params to set up the test.

Example:

class SomethingController {
    def search = {
        def query = params.query
        ...stuff...
        render results as JSON
    }
}

The test looks like:

class SomethingControllerTests extends grails.test.ControllerUnitTestCase {
    void testSearch() {
        controller.params.query = "test query"
        controller.search()
        assertEquals "expected result", controller.response.contentAsString
    }
}

Note: you can use ControllerUnitTestCase for integration tests too, if you need a full integration environment complete with database.

like image 55
ataylor Avatar answered Sep 22 '22 02:09

ataylor