Grails 3.2.7 使用 http 方法测试 url 映射

Grails 3.2.7 test url mappings with http method

在 Grails 中,我有如下 UrlMappings:

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

我想为这些映射编写单元测试,但是我无法在 documentation 中找到如何使用 Http 方法 url 映射测试。

我试过将方法参数添加到断言中,但它不起作用

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

有什么办法吗?

编辑:

上面的第二个测试失败并显示 junit.framework.ComparisonFailure: Url mapping action assertion for '/route' failed expected:<[save]> but was:<[index]> 消息。

主要问题是 assertUrlMapping 似乎只适用于 GET 请求。

我已经通过将映射更改为:

对其进行了试验
static mappings = {
    '/route'(controller: 'route') {
        action = [POST: 'createRoute', PUT: 'updateRoute']
    }
}

和测试:

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

失败并显示以下消息:

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]>

尝试修改您的测试以在请求中指定 http 方法。像这样(使用 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()
}

我也为这个问题苦苦挣扎。我在 source code for a grails test suite.

中找到了这个解决方案