I am trying to test the behaviour of a Grails controller. The controllers answers with a JSON Object. The next function fails
void testEnable() {
def controller = new UserController()
controller.enable()
assertEquals('{"errors":"No se puede completar la petición porque faltan parametros"}', controller.response.contentAsString)
controller.params.enabled = "foo"
controller.enable()
assertEquals('{"errors":"No se puede completar la petición porque faltan parametros"}', controller.response.contentAsString)
controller.params.enabled=true
controller.params.id=2
controller.enable()
/* Next line fails */
assertEquals('{"errors":"No se ha encontrado al usuario"}', controller.response.contentAsString)
}
I am getting the next error:
null expected:<{"errors":"No se [ha encontrado al usuario]"}> but was:<{"errors":"No se [puede completar la petición porque faltan parametros]"}>
However, If I split the test in two functions, both function passes.
void testEnableGoodParameters() {
def controller = new UserController()
controller.params.enabled=true
controller.params.id=2
controller.enable()
assertEquals('{"errors":"No se ha encontrado al usuario"}', controller.response.contentAsString)
}
void testEnableBadParameters() {
def controller = new UserController()
controller.enable()
assertEquals('{"errors":"No se puede completar la petición porque faltan parametros"}', controller.response.contentAsString)
controller.params.enabled = "foo"
controller.enable()
assertEquals('{"errors":"No se puede completar la petición porque faltan parametros"}', controller.response.contentAsString)
}
So, It seems controller.response is no being changed. Does anyone knows why is this happening and how to get around it?
A
MockHttpServletResponseis injected on Controller creation, not before every controller action call.When you call controller method more than once in one test, all calls use the same injected response. From what I understand, render() method does not overwrite previously rendered response, but appends to it – so, in your example, when you call
enable()for the third time, response already contains json objects rendered on previous calls.Also, your error message doesn’t look like it was thrown by the third assertion, but the first or second one.