gpt4 book ai didi

xml - Grails - 测试 XML 请求未按预期运行

转载 作者:数据小太阳 更新时间:2023-10-29 02:45:08 24 4
gpt4 key购买 nike

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

在规范中:

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

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

在 Controller 中:

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 ,我将 Controller 代码更新为以下内容:

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

并且有效。当然,我可以使用它作为变通方法,但这并不能解决 request.XML 的意外行为。它为 null,这意味着不会自动解析请求正文。

最佳答案

看来你的根标签被翻译成了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

关于xml - Grails - 测试 XML 请求未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com