首页 > 解决方案 > 如何在 JMeter 中对 JSR223 断言中的多个字段执行验证

问题描述

我在 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,“头像”:“https://reqres.in/img/faces/9-image.jpg”,“first_name”:“Tobias”,“email”:“tobias.funke@reqres.在“},{“姓氏”:“字段”,“id”:10,“头像”:“https://reqres.in/img/faces/10-image.jpg”,“first_name”:“拜伦”,“电子邮件”:“byron.fields@reqres.in”},{“last_name” “:“爱德华兹”,“id”:11,“头像”:“https://reqres.in/img/faces/11-image.jpg”,“名字”:“乔治”,“电子邮件”:“乔治.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
if (email != 'test' ) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage("Incorrect email value" + email)
}
if (lastName != 'test') {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage("Incorrect last name value\n" +姓氏)
​​}

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

标签: jmeterassertion

解决方案


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

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)
}

更多信息:


推荐阅读