I've been trying to define a test for consuming XML formatted request but I'm always getting null
values. Here's the code:
In the spec:
void "Test XML"() {
when:
controller.request.xml = '<book><title>My Book</title></book>'
controller.doStuff()
then:
response.text == "Book title: My Book"
}
In the controller:
def doStuff() {
request.withFormat {
xml { render "Book title: ${request.XML?.book?.title}" }
}
}
This is pretty similar to what the official docs describe. However, I always get:
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
when I run the test. My JSON tests that follow the same pattern are fine though.
Update
Based on this StackOverflow question, I updated the controller code to the following:
def doStuff() {
request.withFormat {
xml {
def book = new XmlSlurper().parseText(request.reader.text)
render "Book title: ${book.title}"
}
}
}
and it works. I could use this as a work around, of course, but this doesn't answer the unexpected behavior of request.XML
. It's null, which means that the request body doesn't get parsed automatically.