Finding XML element from RESTClient with XMLSlurper
I'm writing a Spock test, in which I have a REST web service that returns an XML like this:
<templates>
<userTemplate id="1109">
<settingsXml/>
<type>USER</type>
<label>template111</label>
<description>template111</description>
</userTemplate>
<userTemplate id="1141" isAutomaticTemplate="true">
<settingsXml/>
<type>USER</type>
<label>An updated user template</label>
</userTemplate>
</templates>
My test want to verify that a particular userTemplate it is not in this document. So, using HTTP Builder's REST client and XMLSlurper, I'm doing the following:
res = settingsService.get(path: "templates")
res.status == 200
def delTemplate = res.data.userTemplate.find {
println it.@id == newUserTemplateId
it.@id == newUserTemplateId
}
delTemplate
I would have thought that delTemplate would be null after calling find (because there's no template with that id; the expresion println it.@id == newUserTemplateId always prints false, in this case the value of newUserTemplateId is 1171).
However, delTemplate is of type groovy.util.slurpersupport.NoChildren, and it seems to contain a userTemplate element.Funny thing is if I write a quick script with the same XML as text (as oppossed of reading it from REST), res.userTemplate.find { it.@id == 1171 }
returns null a开发者_如何学编程s expected.
What am I doing wrong, or how could I solve this?
I use httpBuilder with XMLSlurper for JUnit testing of rest webservices. There is a gotcha that find() on a GPathResult always returns another GPathResult - but that this might contain no children.
For your particular usecase, the idiom I'd use would be:
def resp = settingsService.get(path: 'templates')
assert resp.success
assert resp.data.userTemplate.find {it.@id == newUserTemplateId}.isEmpty()
精彩评论