unit-testinggrailsurl-mapping

Grails 3.2.7 test url mappings with http method


In Grails I have UrlMappings as follows:

static mappings = {
    '/route'(controller: 'route') {
        action = [POST: 'save', GET: 'index']
    }
}

I wanted to write unit tests for those mappings, however I cannot find in documentation how to use Http method url mapping test.

I have tried adding method parameter to the assertions, but it does not work

assertUrlMapping([controller: 'route', action: 'index', method: 'GET'], '/route')
assertUrlMapping([controller: 'route', action: 'save', method: 'POST'], '/route')

Is there any way to do this?

EDIT:

The second one of the tests above fails with junit.framework.ComparisonFailure: Url mapping action assertion for '/route' failed expected:<[save]> but was:<[index]> message.

The main problem is that assertUrlMapping seems to work only for GET requests.

I have experimented with it by changing my mappings to:

static mappings = {
    '/route'(controller: 'route') {
        action = [POST: 'createRoute', PUT: 'updateRoute']
    }
}

and the tests to:

assertUrlMapping([controller: 'route', action: 'updateRoute', method: 'PUT'], '/route')
assertUrlMapping([controller: 'route', action: 'createRoute', method: 'POST'], '/route')

This failed with the following messages:

junit.framework.ComparisonFailure: Url mapping action assertion for '/route' failed expected:<[updateRoute]> but was:<[index]>
junit.framework.ComparisonFailure: Url mapping action assertion for '/route' failed expected:<[createRoute]> but was:<[index]>

Solution

  • Try amending your test to specify the http method in the request. Something like this (using Spock):

    def "test url mappings" () {
        when:
            request.method = "GET"
            assertUrlMapping("/route", controller: "route", action: "index", method: "GET")
        then:
            noExceptionThrown()        
        when:
            request.method = "POST"
            assertUrlMapping("/route", controller: "route", action: "save", method: "POST")
        then:
            noExceptionThrown()
    }
    

    I also struggled with this issue. I found this solution in the source code for a grails test suite.