Forum Discussion

Burned357Waffle's avatar
Burned357Waffle
New Contributor
6 years ago

How to get a specific response from a TestCase with Groovy Script

Hello, I am trying to get a response from one of my TestCases using Groovy Script. I have the following and it gives me the Xml, but how do i pull out only the serial_number?

 

String temp = testRunner.testCase.testSteps.("TestCase").testRequest.response.getContentAsXml();

log.info(temp)

 

in the log i get this:

Tue Jul 16 23:27:51 UTC 2019: INFO: <Response xmlns="http://localhost/v1.0.0/vnms/">
<serial_number>102930478390026</serial_number>
<site_id>a2db3129-172a-704b994c</site_id>
</Response>

  • There are several ways to interact with XML strings, my preferred approach is the XmlSlurper, the following is a standalone example with your XML data:

     

    import groovy.util.XmlSlurper
    
    def xmlData = '''\
    <Response xmlns="http://localhost/v1.0.0/vnms/">
    	<serial_number>102930478390026</serial_number>
    	<site_id>a2db3129-172a-704b994c</site_id>
    </Response>'''
    
    
    def Response = new XmlSlurper().parseText(xmlData)
    def serialNumber = Response.serial_number.text()
    
    log.info('Serial Number = ' + serialNumber)

    The following page has all the details about the XmlSlurper

     

    https://groovy-lang.org/processing-xml.html

4 Replies

  • Radford's avatar
    Radford
    Super Contributor

    There are several ways to interact with XML strings, my preferred approach is the XmlSlurper, the following is a standalone example with your XML data:

     

    import groovy.util.XmlSlurper
    
    def xmlData = '''\
    <Response xmlns="http://localhost/v1.0.0/vnms/">
    	<serial_number>102930478390026</serial_number>
    	<site_id>a2db3129-172a-704b994c</site_id>
    </Response>'''
    
    
    def Response = new XmlSlurper().parseText(xmlData)
    def serialNumber = Response.serial_number.text()
    
    log.info('Serial Number = ' + serialNumber)

    The following page has all the details about the XmlSlurper

     

    https://groovy-lang.org/processing-xml.html

    • Burned357Waffle's avatar
      Burned357Waffle
      New Contributor

      Hi, thank you for the response, i was wondering if ther is any way to use the "temp" variable in xmlData because i cannot hard code it in.

       

      i am also just an intern at the moment, so i do not know much.

       

      -thank you

      • nmrao's avatar
        nmrao
        Champion Level 3
        You just need to change first statement

        def xmlData = testRunner.testCase.testSteps.("TestCase").testRequest.response.getContentAsXml()

        Rest of the script will be same