Forum Discussion
NehaLadani
3 years agoOccasional Contributor
Hello KarelHusa,
Greetings!
I might have not explained it well.
The above link is mot my requirement.
My exact question is - how to handle the list in response while writing assertions?
TNeuschwanger
3 years agoCommunity Leader
Hello NehaLadani
Here is a code sample for you. Your output json was not syntactically correct when dropped into a json editor (https://jsoneditoronline.org), so I took the liberty to adjust it a little bit so that a code sample could be created... I don't know assert requirements, so I just added a few to display what they might look like.
import groovy.json.JsonSlurper;
log.info 'Test Step "' + testRunner.runContext.currentStep.name + '" start...';
log.info "";
def String jsonStr = """
{
"step_list": [
{
"end_date": "2035-09-01T00:00:00",
"payments": 12,
"sequence": 1
},
{
"end_date": "2035-09-01T00:00:00",
"payments": 67,
"sequence": 2
}
]
}
""";
def jsonSlurper = new JsonSlurper();
def jsonObj = jsonSlurper.parseText(jsonStr);
log.info "jsonObj=$jsonObj";
def expectedSize = 2;
assert jsonObj.step_list.size() == expectedSize, "Expected step_list size to be $expectedSize but it is = ${jsonObj.step_list.size()}";
log.info "jsonObj.step_list.first()=${jsonObj.step_list.first()}";
log.info "jsonObj.step_list.last()=${jsonObj.step_list.last()}";
def datePattern = "yyyy-MM-dd";
jsonObj.step_list.each { step ->
log.info "";
log.info "step=${step}";
def stepDate = Date.parse(datePattern, step.end_date);
log.info "stepDate=${stepDate}";
Date lowDate = new Date("08/15/2020");
Date highDate = new Date("10/15/2040");
def nowDate = new Date();
assert stepDate > lowDate, "Expected the step date to be greater than $lowDate but it is $stepDate";
assert stepDate < highDate, "Expected the step date to be less than $highDate but it is $stepDate";
assert stepDate > nowDate, "Expected the step date to be greater than today but it is $stepDate";
def expectedPaymentMinimum = 10;
assert step.payments > expectedPaymentMinimum , "Expected the step payments to be greater than $expectedPaymentMinimum but it is ${step.payments}";
if (step == jsonObj.step_list.first()) {
log.info "step.sequence=${step.sequence}";
def expectedFirstSequence = 1;
assert step.sequence == expectedFirstSequence, "Expected the first step sequence to be $expectedFirstSequence but it is = ${step.sequence}";
};
if (step == jsonObj.step_list.last()) {
log.info "step.sequence=${step.sequence}";
def expectedLastSequence = 2;
assert step.sequence == expectedLastSequence, "Expected the last step sequence to be $expectedLastSequence but it is = ${step.sequence}";
};
};
log.info "";
log.info 'Test Step "' + testRunner.runContext.currentStep.name + '" done...';
Regards,
Todd