1

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 as expected.

What am I doing wrong, or how could I solve this?

mfloryan
  • 7,667
  • 4
  • 31
  • 44
Alex
  • 228
  • 1
  • 10
  • So does your service return an XMLSlurper object? – mfloryan Dec 09 '10 at 13:42
  • It does, as far as I know. RESTClient returns an http://groovy.codehaus.org/modules/http-builder/apidocs/groovyx/net/http/HttpResponseDecorator.htm, with the response data already parsed into an XMLSlurper object. I have fixed this issue now, by using findAll() and then checking for isEmpty(), but I'm still curious why it doesnt't work with find() and checking for null. – Alex Dec 10 '10 at 10:37

1 Answers1

2

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()
winstaan74
  • 1,131
  • 7
  • 11