【问题标题】:Grails - testing XML request does not behave as expectedGrails - 测试 XML 请求的行为不符合预期
【发布时间】:2014-06-26 18:11:52
【问题描述】:

我一直在尝试定义一个使用 XML 格式请求的测试,但我总是得到 null 值。代码如下:

在规范中:

void "Test XML"() {
    when:
    controller.request.xml = '<book><title>My Book</title></book>'
    controller.doStuff()

    then:
    response.text == "Book title: My Book"
}

在控制器中:

def doStuff() {
    request.withFormat {
        xml { render "Book title: ${request.XML?.book?.title}" }
    }
}

这与官方文档描述的非常相似。但是,我总是得到:

response.text == "Book title: My Book"
|        |    |
|        |    false
|        |    7 differences (63% similarity)
|        |    Book title: (null---)
|        |    Book title: (My Book)
|        Book title: null
org.codehaus.groovy.grails.plugins.testing.GrailsMockHttpServletResponse@61a48515

当我运行测试时。不过,遵循相同模式的 JSON 测试很好。

更新

基于this StackOverflow question,我将控制器代码更新为:

def doStuff() {
    request.withFormat {
        xml {
            def book = new XmlSlurper().parseText(request.reader.text)
            render "Book title: ${book.title}"
        }
    }
}

它有效。当然,我可以将其用作解决方法,但这并不能回答request.XML 的意外行为。为null,表示请求体不会被自动解析。

【问题讨论】:

    标签: xml grails testing groovy


    【解决方案1】:

    好像你的根标签被翻译成request.XML,例如:

    class SimpleController {
    
        def consume() {
            request.withFormat {
                xml {
                    render "The XML Title Is ${request.XML.title}."
                }
                json {
                    render "The JSON Title Is ${request.JSON.title}."
                }
            }
        }
    
    }
    
    @TestFor(SimpleController)
    class SimpleControllerSpec extends Specification {
    
        void 'test consume xml'() {
            when:
            request.xml = '<book><title>The Stand</title></book>'
            controller.consume()
    
            then:
            response.text == 'The XML Title Is The Stand.'
        }
    }
    

    请注意,我不是直接访问book.title,而是直接访问title

    【讨论】:

    • 我认为这不是问题所在。正如我所提到的,request.XML 返回 null,因此在其上调用任何内容都会导致 NullPointerException(没有 ? 运算符)。
    • 我认为您的 NullPointer 在书本部分。你试过我的例子吗?
    • 我确定是request.XML,因为错误消息说当我引用request.XML.title 时,无法在空对象上调用属性'title'。
    • 我也在我的测试课中使用request.xml,而你使用的是controller.request.xml。您能否将我的示例复制粘贴到您的项目中,看看它是否有效?
    • 我尝试了所有我能想到的组合,但没有任何效果。您使用的是什么版本的 Grails?
    【解决方案2】:

    为了读取模拟请求 XML 有效负载,必须指定一个方法,而不是默认的 'GET'。

    void "Test XML"() {
       when:
       controller.request.method='POST'
       controller.request.xml = '<book><title>My Book</title></book>'
       controller.doStuff()
       then:
       response.text == "Book title: My Book"
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 2018-03-19
      • 1970-01-01
      • 2017-01-27
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多