如何在 JMeter 中对 JSR223 断言中的多个字段执行验证

时间:2021-07-15 09:24:43

标签: jmeter assertion

我在 JSR223 断言中编写了以下脚本来验证字段。现在我想对多个字段(如名字、电子邮件)执行验证,但我不想为每个字段编写单独的脚本。如何在同一个 JSR223 断言脚本中实​​现这一点?

def responseJson = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def lastName = responseJson.data[0].last_name

if (lastName != 'Lawson') {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage("值不正确" + lastName)
}

下面是Json:
{ "per_page": 6, "total": 12, "data": [ { "last_name": "Lawson", "id": 7, "avatar": " https://reqres.in/img/faces/7-image.jpg", "first_name": "Michael", "email": "michael.lawson@reqres.in" }, { "last_name": "Ferguson" , "id": 8, "avatar": "https://reqres.in/img/faces/8-image.jpg", "first_name": "Lindsay", "email": "lindsay.ferguson@reqres. in" }, { "last_name": "Funke", "id": 9, "avatar": "https://reqres.in/img/faces/9-image.jpg", "first_name": "Tobias" , "email": "tobias.funke@reqres.in" }, { "last_name": "Fields", "id": 10, "avatar": "https://reqres.in/img/faces/10- image.jpg", "first_name": "Byron", "email": "byron.fields@reqres.in" }, { "last_name": "Edwards", "id": 11, "avatar": "https: //reqres.in/img/faces/11-image.jpg", "first_name": "George", "email": "george.edwards@reqres.in" }, { "last_name": "Howell", " id": 12, "avatar": "https://reqres.in/img/faces/12-image.jpg", "first_name": "Rachel", "email": "rachel.howell@reqres.in" } ], "page": 2, "total_pages": 2, "support": { "text": "为了保持 ReqRes 免费,感谢对服务器成本的贡献!", "url": "https://reqres.in/#support-heading" } }

我也尝试使用以下脚本,但它只给我姓氏的结果,而不是电子邮件和姓氏的结果:

def responseJson = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def lastName = responseJson.data[0].last_name
def email = responseJson.data[0].email
如果(电子邮件!= '测试'){
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage("不正确的电子邮件值" + 电子邮件)
}
如果(姓氏!= '测试'){
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage("姓氏值不正确\n" + lastName)
}

其他
{ AssertionResult.setFailure(true)
AssertionResult.setFailureMessage("正确值");
}

1 个答案:

答案 0 :(得分:0)

如果您真的“编写”了脚本,那么为姓氏添加更多像这样的检查应该不成问题:

def responseJson = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def lastName = responseJson.data[0].last_name
def email = responseJson.data[0].email

if (lastName != 'Lawson') {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage("Incorrect value" + lastName)
}
if (email != 'michael.lawson@reqres.in') {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage("Incorrect value" + lastName)
}

更多信息: