【问题标题】:Grails 3.2.7 test url mappings with http methodGrails 3.2.7 使用 http 方法测试 url 映射
【发布时间】:2018-02-01 16:52:22
【问题描述】:

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

【问题讨论】:

  • “它不起作用”是什么意思?
  • 第二次测试失败,junit.framework.ComparisonFailure: Url mapping action assertion for '/route' failed expected:&lt;[save]&gt; but was:&lt;[index]&gt;

标签: unit-testing grails url-mapping


【解决方案1】:

尝试修改您的测试以在请求中指定 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 找到了这个解决方案。

【讨论】:

  • 这正是我想要的。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-19
  • 2016-02-16
相关资源
最近更新 更多