我正在学习测试自动化,我尝试使用响应值作为下一个请求输入。问题是响应包括一个可以包含任意数量元素的列表。
代码如下所示:
响应:
{
"idNumber": null,
"response": {
"event": "7b-34g",
"products": [
{
"id": "3464",
"productName": "Hats"
},
{
"id": "3465",
"productName": "Shoes"
}
]
},
"errors": null
}
下一个请求:
{
"customer": "000011223333",
"payment": "visa",
"zzzz": "012345678-9",
"products": [{
"id": ""
}],
"XXXX": {
"YYYY": {
"profile": "Consumer"
}
}
}
产品中的元素数量是任意的,即它可以是任意数量的元素。我尝试了groovy脚本,但无法找到如何做到这一点。我只需要响应中的“产品”列表,并且每个元素我只需要“id”。其余值是静态的。 我很感谢任何帮助 // Mikael
答案 0 :(得分:2)
以下是第一个请求测试步骤的Script Assertion
。
以下脚本执行:
products
详细信息import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
//Provide the name of the next request test step name where you need to override the content
def nextStepName = 'step2'
//DO NOT REQUIRE TO MODIFY
//Check the current step response
assert context.response, 'Response is empty'
def json = new JsonSlurper().parseText(context.response)
def products = json.response.products
log.info "Products details from current response: $products"
//Get the next test step request
def nextStepRequest = context.testCase.testSteps[nextStepName].httpRequest
//Check if the next step request content is empty
assert nextStepRequest.requestContent, "Next step, $nextStepName, request is empty"
def slurped = new JsonSlurper().parseText(nextStepRequest.requestContent)
def builder = new JsonBuilder(slurped)
//Change the products of next request
builder.content.products = products.inject([]){l, item -> def map = [:];map['id'] = item.id; l << map; l}
//Update the product details in the request
nextStepRequest.requestContent = builder.toPrettyString()
log.info "Updated request for the step ${nextStepName} is : ${nextStepRequest.requestContent}"
您可以在线快速尝试 Demo
以上脚本假定测试步骤的名称在脚本的以下语句中为step2
。如果您的情况不同,请更改值。
def nextStepName = 'step2'
答案 1 :(得分:0)
给出产品清单:
products = [[id:123, name:'alpha'], [id:456, name:'beta']]
您可以通过以下方式获取仅包含ID的列表:
products.collect{[id: it.id]}