Groovy script - Sum two values of REST response and pass the sum on to the next request
- 3 years ago
Hi,
Groovy script is a subset of Java and is really, really useful to learn. There's loads of on-line resources for using Groovy scripts.
In terms of what you want, here is the script. Create a Groovy script step, called "Add - Groovy Script" after your web service call and paste in the below....
def valueOne = "4"; // ${TestStep1#Response#$['ABC']['Array'][0]['Price']['value']}; def valueTwo = "8.2"; // ${TestStep1#Response#$['ABC']['Array'][1]['Price']['value']}; try { def valueOneDouble = Double. parseDouble(valueOne); def valueTwoDouble = Double. parseDouble(valueTwo); def answer = valueOneDouble + valueTwoDouble; log.info ("My Sum is ${valueOneDouble} + ${valueTwoDouble} = ${answer}"); def answerString = String.valueOf(answer); // Put the answer into a custom property for the test case. testRunner.testCase.setPropertyValue( "mySum", answerString ); // or simply return it.... return answerString; } catch (NumberFormatException e) { //the parseDouble failed and you need to handle it here. }
Note : for example purposes, I've hard-coded values one and two and commented how you'd access them according to your question.
To use the answer in a subsequent step, you have options. You're already using Property Transfer, but I never have so I don't know if you can transfer the answer from a groovy script.
My example puts the answer into a custom property (like a global variable) at the test case level. You can then access this from another step. Look up custom properties on the SmartBear site.
You can also 'pull' the answer from the Groovy step directly into the subsequent step. If you go the step where you want the answer and edit the payload. When you want the value inserting, type...
${Add - Groovy Script#result}
When ReadyAPI is about to call the 'subsequent' step, it will then call the Groovy script and replace the ${} stuff with the actual value.
- 3 years ago
Hi,
Try wrapping context.expand around your variable.
E.g.
def value = ${CheckContingentStartTimes#Response#$['ContingentStartTimes']['ContingentStartTime'][0]['Price']['value']};
becomes....
def value = context.expand('${CheckContingentStartTimes#Response#$['ContingentStartTimes']['ContingentStartTime'][0]['Price']['value']}}');
But, if you have ReadyAPI then there is a better way....
In the Groovy window, put the cursor near the top and right-click. In the context menu, there is an option called 'Get Data'. Click it. You'll then get another window which will let you navigate through your test structure and actually select the value you want from the service call's response. It will then insert the correct value to access.