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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With