Search code examples
groovysoapuiassertions

How to pick up child element of specific parent element in Script Assertion?


I have the following XML example which shows there are multiple occurrences of node 'ProductCode' which fall under both nodes 'PrevHospProduct' and also under 'PrevExtrasProducts'.

                <ns2:PrevHospProducts>
                    <ns2:PrevHospProduct>
                       <ns2:ProductCode>D00</ns2:ProductCode>
                       <ns2:ExcessPaid>Yes</ns2:ExcessPaid>
                    </ns2:PrevHospProduct>
                    <ns2:PrevHospProduct>
                       <ns2:ProductCode>900</ns2:ProductCode>
                    </ns2:PrevHospProduct>
                 </ns2:PrevHospProducts>
                 <ns2:PrevExtrasProducts>
                    <ns2:PrevExtraProduct>
                       <ns2:ProductCode>00A</ns2:ProductCode>
                    </ns2:PrevExtraProduct>
                 </ns2:PrevExtrasProducts>

For this test I am only interested in the values in 'ProductCode' which are a child of 'PrevHospProduct'. I am not interested in any of the values under 'PrevExtrasProducts'.

I have the following Groovy Script Assertion in SoapUI to pick up values in 'ProductCode' but the test is failing as the actual results are also returning 'D00', '900' and '00A' from the examples response. I only want the expected results to pick values 'D00', '900'.

def expectedCodes = ['D00','900'] 
def pxml = new XmlSlurper().parseText(context.response)
def actualCodes = pxml.'**'.findAll{it.name() == 'ProductCode' }*.text() as List
assert expectedCodes.sort() == actualCodes.sort()

Solution

  • First need to find the parent node i.e., PrevHospProduct and then get the ProductCode.

    Here is the script assertion:

    def expectedCodes = ['D00','900'] 
    def pxml = new XmlSlurper().parseText(context.response)
    def actualCodes = pxml.'**'.findAll{it.name() == 'PrevHospProduct'}*.ProductCode*.text() as List
    log.info actualCodes
    assert expectedCodes.sort() == actualCodes.sort()