jmeter断言之Beanshell断言(判断数据库结果是否符合预期)

jmeter断言之Beanshell断言(判断数据库结果是否符合预期)

该篇文章主要讲一下beanshell断言处理数据库结果。

(一)首先需要添加配置原件JDBC Connection Configuration连接数据库信息,然后发送jdbc请求获取预期结果。我现在使用得是result_variable_name获取得是响应结果集。接下来对数据库结果集对判断。

 (二)解析结果集,对结果集做判断

2.1:获取数据库对象,然后需要明确下该对象的类型,打印的结果如下:为ArrayList类型。

Object dbInfo = vars.getObject("dbinfo");    //数据库对象
log.info("----数据库结果类型:" + dbInfo.getClass().toString());

2021-01-22 17:48:41,004 INFO o.a.j.u.BeanShellTestElement: ----数据库结果类型:class java.util.ArrayList

2.2:接口响应结果与数据库查询结果做对比,符合条件则判断通过,不符合条件则判断失败

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

//获取请求的返回值
String response_data = prev.getResponseDataAsString();

JSONObject responseObj = JSON.parseObject(response_data);   // 响应对象
JSONArray currentBeans = responseObj.getJSONArray("current_beans");

ArrayList dbInfo = vars.getObject("dbinfo");    //数据库对象
Map dbInfoMap = new HashMap();
for(int i = 0; i < dbInfo.size(); i++){
	Map beans = (Map) dbInfo.get(i);
	dbInfoMap.put(beans.get("customer_serial_no"), beans);
}

for(int i = 0; i < currentBeans.size(); i++){
	JSONObject currentBean = currentBeans.getJSONObject(i);
	String customerSerialNo = currentBean.getString("customer_serial_no");
	Map beans = (Map) dbInfoMap.remove(customerSerialNo);
	if(beans == null){
		log.info("流水:" + customerSerialNo + " 返回的数据在库中不存在");
	}
	
	//判断相同key的数据同dbInfo
	Set currentBeanKeySet = currentBean.keySet();
	Iterator iterator = currentBeanKeySet.iterator();
	String currentBeanKey;
	while(iterator.hasNext()){
		currentBeanKey = (String) iterator.next();
		Object currentBeanValueObj = currentBean.get(currentBeanKey);
		String currentBeanValue = currentBeanValueObj == null ? "null" : String.valueOf(currentBeanValueObj);
		Object dbInfoValueObj = beans.get(currentBeanKey);
		String dbInfoValue = dbInfoValueObj == null ? "null" : String.valueOf(dbInfoValueObj);
		
		if(!currentBeanValue.equals(dbInfoValue)){
			log.info("customer_serial_no: "+ customerSerialNo +" 的流水数据字段["+ currentBeanKey +"]不一致,接口返回:" + currentBeanValue + " , 数据库为: " + dbInfoValue);
		}
	}
}

if(!dbInfoMap.isEmpty()){
	log.info("接口未返回的数据库数据:" + JSON.toJSONString(dbInfoMap));
}

 

posted on 2021-01-22 17:54  qiaoli  阅读(738)  评论(0编辑  收藏  举报

导航