How to call call request.JSON multiple times in Grails unit tests?

Viewed 223

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

0 Answers
Related