这种背景下只能选择BeanShell来处理断言、保存信息以及打印特定log了,于是有了下面第一版beanshellimport com.alibaba.fastjson.JSON; // 阿里的jar包
import com.alibaba.fastjson.JSONObject;
import java.util.Date;
import java.text.SimpleDateFormat;
void write2File(String data, String path){
// 该方法用来写入内容到文件,并加上时间
String tm = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")).format(new Date());
FileWriter fstream = new FileWriter(path, true); //FileWriter("file01.txt",true) append mode
BufferedWriter out = new BufferedWriter(fstream);
out.write("[" + tm + "] " + data);
out.write(System.getProperty("line.separator"));
out.close();
fstream.close();
}
if ("200".equals(""+ResponseCode) == false ){
var errorFile = "errorFile.txt";
write2File(prev.getResponseDataAsString(), errorFile); // 写入error信息到errorFile.txt
Failure=true ; // 设置断言为false
FailureMessage ="Exception,fail! Response code is " + ResponseCode; // 设置断言message
// 打印log,ctx.getThreadNum()代表当前线程,ctx.getThreadGroup().getNumThreads()代表当前活跃的总线程数
log.warn(FailureMessage + ". Current threadNum is " + ctx.getThreadNum() + " of " + ctx.getThreadGroup().getNumThreads());
}else{
var respBody = prev.getResponseDataAsString();
// 因为response是JSON格式,这里用JSON包处理
JSONObject respJson = JSON.parseObject(respBody);
if (respJson.containsKey("data")){
Failure=false;
FailureMessage = "Return true, and the response code was " + ResponseCode;
}else if (respJson.containsKey("x")){
var x = respJson.getString("x");
if (x.contains("connection issue")){
var issueFile = "issueFile.txt";
write2File(x, issueFile);
Failure= true;
FailureMessage= "connection issue,fail!";
log.warn(FailureMessage + " Current threadNum is "+ ctx.getThreadNum() + " of " + ctx.getThreadGroup().getNumThreads());
}else{
var exceptionFile = "exceptionFile.txt";
write2File(x, exceptionFile);
Failure=false;
FailureMessage = "Return exception, and the response code was " + ResponseCode;
}
}else{
Failure= true;
FailureMessage= "Unknow error: " + respBody;
log.warn(FailureMessage + ". Current threadNum is "+ ctx.getThreadNum() + " of " + ctx.getThreadGroup().getNumThreads());
}
}