Search code examples
testingsoapcucumberbddkarate

Assigning multiple JSON values to XML file which returned from a Database call on Karate


For a test project, I am making a call to database, and getting necessary fields which I am going to set in my xml file to make a SOAP service call.

As far as I see, the database call returns as JSON value, so that I am having some trouble to assign values to "some" parts of my xml.

Let's say I have a .xml file which is like below:

<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xxxxxx>
<soapenv:Header/>
<soapenv:Body>
<int:createSubscriber soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <custBean xxxxx>
        <accountNumber xsi:type="xsd:string">#(accountNo)</accountNumber>
        <custName xsi:type="xsd:string" xs:type="type:string">Xbox</custName>
    </custBean>
    <addSubscriberBean xxxxx>7
        <subscriberID xsi:type="xsd:string">#(subsID)</subscriberID>
        <password xsi:type="xsd:string" xs:type="type:string">0</password>
        <areaID xsi:type="xsd:string" xs:type="type:string">1</areaID>
        <lineOfCredit xsi:type="xsd:int" xs:type="type:int"></lineOfCredit>
        <creditCycle xsi:type="xsd:int" xs:type="type:int"></creditCycle>
        <points xsi:type="xsd:int" xs:type="type:int"></points>
        <bandwidth xsi:type="xsd:int" xs:type="type:int"></bandwidth>
        <physicalPorts xsi:type="xsd:string" xs:type="type:string">8080</physicalPorts>
        <mobilePhoneNo xsi:type="xsd:string" xs:type="type:string">#(mobile)</mobilePhoneNo>
        <stbCount xsi:type="xsd:int" xs:type="type:int">5</stbCount>
        <oTTCount xsi:type="xsd:int" xs:type="type:int">10</oTTCount>
        <subscriptionType xsi:type="xsd:string" xs:type="type:string">#(subsType)</subscriptionType>
    </addSubscriberBean>
    <sequenceID xxxxx>1234567840123422700</sequenceID>
</int:createSubscriber>

And then I am making a call to database, so that I am getting below response:

[
{
"ACCOUNT_NO": "123",
"SUBSCRIBER_ID": "123456",
"MOBILE": "123456789",
"SUBSCRIBER_TYPE": "XXXX"
},
{
"ACCOUNT_NO": "456",
"SUBSCRIBER_ID": "456789",
"MOBILE": "456789123",
"SUBSCRIBER_TYPE": "YYYY"
}
]

So I have 2 object returned as you can see above, which means I need to assign those values to the variables dynamically.

Couldn't find a clue to lead me to a solution where I can transform my JSON type values to assign them to my XML based variables.


Solution

  • Loop over the JSON and build an XML.

    * def xml = <users></users>
    * def fun =
    """
    function(u, i) {
      var base = '/users/user[' + (i + 1) + ']/';
      karate.set('xml', base + 'account', u.accountNo);
      karate.set('xml', base + 'mobile', u.mobile);
      karate.set('xml', base + 'type', u.subsType);
    }
    """
    * karate.forEach(users, fun)