How to loop through karate response array and pass

2019-08-09 22:51发布

问题:

I am using Karate version 0.8.0.1 and I want to perform following steps to test some responses.

  1. I make a Get to web service 1
  2. find the value for currencies from the response of web service 1 using jsonpath: $.currencies
  3. Step 2 gives me following result: ["USD","HKD","SGD","INR","GBP"]
  4. Now I use Get method for web service 2
  5. From the response of web service 2 I want to get the value of price field with json-path something like below(passing the values from step 3 above):

    • $.holding[?(@.currency=='USD')].price
    • $.holding[?(@.currency=='HKD')].price
    • $.holding[?(@.currency=='SGD')].price
    • $.holding[?(@.currency=='INR')].price
    • $.holding[?(@.currency=='GBP')].price

So there are so many currencies but I want to verify price for only the currencies returned by web service 1(which will be always random) and pass it on to the the output of web service 2 to get the price. Once i get the price I will match each price value with the value returned from DB.

I am not sure if there is any simple way in which I can pass the values returned by service 1 into the json-path of service 2 one by one and get the results required. Any suggestions for doing this will be helpful As this will be the case for most of the web services I will be automating.

回答1:

There are multiple ways to do this in Karate. The below should give you a few pointers. Note how there is a magic variable _$ when you use match each. And since you can reference any other JSON in scope, you have some very powerful options.

* def expected = { HKD: 1, INR: 2, USD: 3}
* def response1 = ['USD', 'HKD', 'INR']
* def response2 = [{ currency: 'INR', price: 2 }, { currency: 'USD', price: 3 }, { currency: 'HKD', price: 1 }]
* match response2[*].currency contains only response1
* match each response2 contains { price: '#(expected[_$.currency])' }

You probably already have seen how you can call a second feature file in a loop which may be needed for your particular use case. One more piece of the puzzle may be this - it is very easy to transform any JSON array into the form Karate expects for calling a feature file in a loop:

* def response = ['USD', 'HKD', 'INR']
* def data = karate.map(response, function(x){ return { code: x } })
* match data == [{code: 'USD'}, {code: 'HKD'}, {code: 'INR'}]


标签: karate