2

I am upgrading my application from Grails 2.5.6 to Grails 4.0.3. Now I have lots of unit tests failed because I am calling controller methods with request.JSON multiple times in a single test. Those unit tests worked fine in old Grails 2.5.6.

To demonstrate the problem, I have a controller with the following method:

class TestController {
    def testJson(){
        def json = request.JSON
        render(contentType:'application/json', text:json.toString(), encoding: "UTF-8")
    }
}

And I have a unit test like this:

class TestControllerSpec extends Specification implements ControllerUnitTest<TestController> {

    void "test json"(){
        when:
        request.json = [
                a:1, b:2, c:3
        ]
        controller.testJson()

        then:
        response.json.a == 1
        response.json.b == 2
        response.json.c == 3

        when:
        response.reset()
        request.json = [
                a:10, b:20, c:30
        ]
        controller.testJson()

        then:
        response.json.a == 10 // <-- test failed here
        response.json.b == 20
        response.json.c == 30
    }

}

The test will fail with the following error

response.json.a == 10
|        |    | |
|        |    1 false
|        [a:1, b:2, c:3]

The question is: how can I reset the state of the request? or why I cannot set new value to request.json?

Updated: Please check this demo project: https://github.com/jaguar1975cn/grails403test

James Zeng
  • 53
  • 7
  • Try solutions mentioned in the post -- https://stackoverflow.com/questions/18762871/how-to-make-multiple-requests-with-different-data-in-grails-integration-tests – MKB May 07 '20 at 12:01
  • @MKB, I understand you are suggesting to use `where` to work around it. I knew it will work, because if we use `where`, it actually executes those requests separately. But I have thousands of tests need to be refactored, it will be a huge work. – James Zeng May 07 '20 at 12:12
  • Did you also notice in the other answer that there was a comment mentioning to use `controller.params.JSON` instead of `controller.request.JSON`? – kriegaex May 08 '20 at 05:51
  • @kriegaex thanks, `controller.params.JSON` doesn't work either. Same result. – James Zeng May 11 '20 at 21:36
  • What about `controller.response.reset()`? Otherwise maybe sharing an [MCVE](https://stackoverflow.com/help/mcve) on GitHub would be nice. I know some Spock, but zero Grails. An MCVE would be the only way for me to inspect this for you. – kriegaex May 12 '20 at 06:39
  • @kriegaex, `response.reset()` and `controller.response.reset()` are basically the same thing. So it makes no difference. – James Zeng May 12 '20 at 12:47
  • @kriegaex I updated the question. A demo project has been added. Thanks. – James Zeng May 12 '20 at 13:02

0 Answers0