Home > database >  How to set a variable in the xml per scenario
How to set a variable in the xml per scenario

Time:05-23

I have this xml below which I setup in the Background:

* def Request = 
"""
                    <new1:Account>
                        <shar:PaidMode>#(PaidMode)</shar:PaidMode>
                        <shar:BillCycleCredit>#(BillCycleCredit)</shar:BillCycleCredit>
                        <shar:CreditCtrlMode>#(CreditCtrlMode)</shar:CreditCtrlMode>
                        <new1:BillCycleType>#(BillCycleType)</new1:BillCycleType>
                    </new1:Account>
"""

With my test as follows:

Scenario: Create first subscriber
    * def PaidMode = '0'
    And request Request 
    When method Post
    Then status 200
    * print Request

But I cant seem to get this PaidMode to be 0 :( I've read this

Karate API pass def variable in XML

which led me to this (thank you Peter!)

https://github.com/karatelabs/karate#embedded-expressions

its simple, I'm sure, its just not obvious to me what I'm doing wrong

CodePudding user response:

Everything looks fine to me. But: make sure you set the variable 'paidMode' before you declare the xml variable 'body' ! Maybe that's what you missed.

Try this example, which should work:

* def paidMode = 'foo'
* def body = 
"""
<new1:Account>
    <shar:PaidMode>#(paidMode)</shar:PaidMode>
</new1:Account>
"""


* url 'https://httpbin.org/anything'
* request body
* method post

Now, if you really have a need to have the XML "pre set" you can use the set keyword to make an update like this:

* def body = 
"""
<new1:Account>
    <shar:PaidMode></shar:PaidMode>
</new1:Account>
"""
* set body/Account/PaidMode = 'foo'

One trick is to read the XML from a file, so you get the benefit of re-use which you seem to be going for:

* def paidMode = 'foo'
* def body = read('some.xml')
  • Related