Jmeter之BeanShell 断言

作者:季沐测试笔记
博客主页:https://blog.csdn.net/weixin_45630042

1 BeanShell 断言之实例介绍

1.1 假设当前有个判断该用户是否为新用户的接口,返回的数据格式为以下内容:

{
	"success": true,
	"code": 0,
	"msg": "success",
	"data": {
		"newUser": true,
		"invitationCode": null
	},
	"total": 0
}
  • 当用户为新用户时,newUser的值为true

  • 当用户已是老用户时,newUser的值为false

1.2 假设有两为用户:15293561001为老用户,15293561002为新用户,现需要对改接口返回的数据进行验证,看是否达到预期效果,在Jmeter断言中选择BeanShell 断言

BeanShell中的脚本内容的验证就是根据用户判断newUser的值是否正确,这里会用到BeanShell断言的一些语法,只需要判断下后定义下断言失败或是成功即可,断言内容为以下内容

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;

		prev.setDataEncoding("UTF-8");

		String result = prev.getResponseDataAsString();

		String result = prev.getResponseDataAsString();
	
		System.out.println("------------------------------------------------------");
	
		JSONObject response = JSON.parseObject(result);
	
		System.out.println("response为"+response);
	
		JSONObject data = (JSONObject) response.get("data");
	
		System.out.println("data为"+data);
	
		System.out.println("mobile为"+"${mobile}");
	
		System.out.println("newUser为"+data.get("newUser"));
	
	       	if ( "${mobile}" == "15293561001") {
	            	if (data.get("newUser").toString().equals("false")){
	                	Failure = false;
	                	FailureMessage = "断言成功";
	            	}else {
	                	Failure = true;
	                	FailureMessage = "断言失败,newUser为"+data.get("newUser");
	            	}
	        	}else if ("${mobile}" == "15293561002"){
	            	if (data.get("newUser").toString().equals("true")){
	                	Failure = false;
	                	FailureMessage = "断言成功";
	            	}else {
	                	Failure = true;
	                	FailureMessage = "断言失败,newUser为"+data.get("newUser");
	            	}
	        	}

断言中15293561001判断的newUser为false,15293561002判断的newUser为true,该断言应该完全通过,循环请求该接口,察看结果树

两条数据都是断言通过

下面我们将15293561002的newUser断言处改为false,执行效果如下

可以看到显示出了之前定义的断言失败的信息和接口返回的该字段的实际结果。

2 断言语法介绍

示例:

if (data.get("newUser").toString().equals("true")){
		Failure = false;
		FailureMessage = "断言成功";
	}else {
		Failure = true;
	    FailureMessage = "断言失败,newUser为"+data.get("newUser");
	}

以上断言信息中Failrue用来标识断言失败,Failure = false;时表示断言成功
FailureMessage标识断言失败的原因

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值