记一次JMeter写java脚本代码

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

背景

搭建接口自动化平台,是在windows下调试,最终在linux环境运行,那么在保存结果路径方面存在差异,所以为了能在两边环境跑通,对于路径斜杠需要参数化处理;java支持调用系统函数,获取当前执行的系统属性,决定使用那个路径变量,Beanshell脚本编写,类同python可以直接定义函数,使用系统自带的类方法。

beanshell编码

打开jmeter创建线程组,添加beanshell处理器

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

//java 脚本可以不需要class类来装饰,可以直接写方法,jdk1.5以上支持泛型java语法
//public class AppendFile {
//将content写入到指定文件fileName中
public static void appendFile(String fileName, String content) throws IOException{
 FileWriter writer = null;
try {
 writer = new FileWriter(fileName, true); //true 换行追加记录,false每次执行替换
 content = content + "\n";
 writer.write(content);
 } catch(IOException e){
 e.printStackTrace();
 }finally{
 if (writer != null){
 writer.close();
      }
    } 
}
//}
//判断当前系统是否为linux
public static boolean isLinux() {
return System.getProperties().getProperty("os.name").toLowerCase().indexOf("linux") >= 0;
}
//System.out.println("******写入文件start*******");
//xxx,userTypr,nickName,account,passwd
String getdata1 = vars.get("caseid");
String getdata2 = vars.get("title"); //此处的username就是从sample中获取的变量名,根据实际情况修改。
String getdata3 = vars.get("params");
String getdata4 = vars.get("requri");
//String getdata5 = vars.get("A");
//String getdata6 = vars.get("B");
//String getdata7 = vars.get("C");
String expected=vars.get("expect");
String res=prev.getResponseDataAsString();
if(!res.contains(expected)){
		Failure=true;
		FailureMessage = "响应结果 don't contains keywords:"+expected+",断言失败!预期结果与实际不符!";
		if (isLinux()){
		String filePath = "/var/lib/jenkins/workspace/Hcp_Api_Auto/errorData.csv";
		//		想把每次断言失败的结果给写入csv表格
		appendFile(filePath,getdata1+','+getdata2+','+getdata3+','+getdata4+','+FailureMessage);
		}else{
		String filePath = "D:/errorData.csv";
		//		想把每次断言失败的结果给写入csv表格
		appendFile(filePath,getdata1+','+getdata2+','+getdata3+','+getdata4+','+FailureMessage);
		}
	}else{
		FailureMessage = prev.getResponseDataAsString() +"contains keywords: "+expected+"断言成功!预期结果与实际一致!";
	}
//log.info(FailureMessage);
//System.out.println("******写入文件end*******");
复制代码

脚本中有个问题,在IDE工具中封装方法时,有些异常是直接抛出,并没有try...catch捕获异常,这个是否在导出的jar放在jmeter环境中导入调用可能会报错,这时需要在beanshell脚本中try...catch一下?

猜测

在IDE工具中try-catch,需要在jmeter引入调用时try-catch处理异常,如果时throws抛出的异常,则调用封装的方法时不需要处理。

猜你喜欢

转载自juejin.im/post/7018352674542698504