如何解决如何使用 beanshell 断言将 JSON 值提取到字符串变量中以验证必填字段
我在 Beanshell 断言中编写了以下脚本来验证某些特定值:
导入 org.json.*;
导入 org.json.JSONArray;
导入 org.json.JSONException;
导入 org.json.JSONObject;
String jsonString = prev.getResponseDataAsString();
JSONObject responseJson = new JSONObject(jsonString);
String lastName = responseJson.getString("$data[0]."{last_name}"");
String Message="";
if (lastName== "lawson")
{
失败=假;
Message= Message+"正确值";
FailureMessage=消息;
}
否则如果(姓氏!=“劳森”)
{
失败=真;
Message= Message+“值不正确”+lastName;
FailureMessage=消息;
}
下面是Json: { “每页”:6, “总计”:12, “数据”: [ { "last_name": "劳森",“身份证”:7, "头像": "https://reqres.in/img/faces/7-image.jpg","first_name": "迈克尔",“电子邮件”:“michael.lawson@reqres.in” },{ "last_name": "弗格森",“身份证”:8, "头像": "https://reqres.in/img/faces/8-image.jpg","first_name": "林赛",“电子邮件”:“lindsay.ferguson@reqres.in” },{ "last_name": "Funke",“身份证”:9, "头像": "https://reqres.in/img/faces/9-image.jpg","first_name": "托比亚斯",“电子邮件”:“tobias.funke@reqres.in” },{ "last_name": "字段",“身份证”:10, "头像": "https://reqres.in/img/faces/10-image.jpg","first_name": "拜伦",“电子邮件”:“byron.fields@reqres.in” },{ "last_name": "爱德华兹",“身份证”:11, "头像": "https://reqres.in/img/faces/11-image.jpg","first_name": "乔治",“电子邮件”:“george.edwards@reqres.in” },{ "last_name": "豪厄尔",“身份证”:12, "头像": "https://reqres.in/img/faces/12-image.jpg","first_name": "瑞秋",“电子邮件”:“rachel.howell@reqres.in” } ],“第2页, "total_pages": 2,“支持”: { "text": "为了保持 ReqRes 免费,感谢对服务器成本的贡献!","url": "https://reqres.in/#support-heading" } }
但我收到以下错误:
断言失败消息:org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval In file: inline evaluation of: ``import org.json.*;导入 org.json.JSONArray;导入 org.json.JSONException;小鬼. . '' 在第 9 行第 41 列遇到 "( "$data[0]." { last_name } """。
有人可以帮助我在我的脚本中犯什么错误吗?
解决方法
您的代码存在多个问题,例如:
- 我认为 JSONObject.getString() 不接受 JsonPath,它只接受 JSON 对象键名
- 您应该使用 equals() function 比较字符串
- 字符串区分大小写,
lawson
和Lawson
是不同的实体 - Since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language 用于编写脚本
因此,如果您想继续使用基于代码的方法,JSR223 Assertion 的最小等效代码将类似于:
def responseJson = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def lastName = responseJson.data[0].last_name
if (lastName != 'Lawson') {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage("Incorrect value" + lastName)
}
请注意,您可以使用 JSON Assertion:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。