Search code examples
xmlgroovyassert

Asserting specific xml tag from a document with Groovy


I want to create a groovy script that will assert if a document or xml file contains a tag that contains also a specific value. I think I can define the file like this:

String fileContents = new File('/path/to/file').getText('UTF-8')

But I have struggle how to define the assertion. Lets say that this xml file that I want to check should contain a tag that is named <ApplicationID> with value 12345. How can I verify that <ApplicationID>12345</ApplicationID> is contained in the specific file?


Solution

  • You can look at the file as raw text, as:

    assert new File('somefile').text.contains('<ApplicationID>12345</ApplicationID>')
    

    or, parse the XML and specify the location in the XML for the data you want to check on.

    Given:
        new File("somefile.xml").text = 
         '<someXml><someTag><ApplicationID>12345</ApplicationID></someTag></someXml>'
    
    Then:
        assert new XmlSlurper()
         .parseText(new File("somefile.xml").text)
         ."someTag"."ApplicationID".text() == "12345"