Jmeter自動化測試常見的問題解決方案匯總
一、如何解決response內容中文亂碼問題?
解決方案:添加一個BeanShell PreProcessor,然后在Script代碼區域添加:prev.setDataEncoding("utf-8");
如圖:

二、如何提取response中json格式的內容?
解決方案:在請求Samper,添加一個后置處理器(Json提取器)。
格式:$.data.report.reportCode
data代表父節點,report代表子節點,reportCode代表子節點下面的節點,用點來一層一層定位。
例子:

三、關于BeanShell參數傳遞如何使用?
解決方案:右鍵添加一個BeanShell PostProcessor, 將前面提取出來的參數,以java代碼傳入到嵌入的腳本中。
代碼:String reportCode = vars.get("reportCode");
例子:

四、如何使用BeanShell處理response 中json格式的內容。
解決方案:
步驟1:添加一個json.jar 包。下載地址:https://mvnrepository.com/artifact/org.json/json/20180813
步驟2:將json.jar包添加到D:pache-jmeter-2.13libext 和 D:pache-jmeter-2.13lib 目錄中
步驟3:在測試計劃中添加json.jar 包,界面最下面,Add directory or jar to classpath
步驟4: 重啟jmeter
步驟5:添加一個BeanShell PostProcessor,使用java代碼解析json,
代碼例子:
import org.json.*; //獲取獲取請求的返回值 String response_data = prev.getResponseDataAsString(); //日志打印獲取請求的返回值 //log.info(response_data); //將String類型的返回值構造成JSONObject對象 JSONObject data_obj = new JSONObject(response_data); //獲取data里面的內容 String list_str = data_obj.get("data").toString(); //JSONArray list_str = data_obj.getJSONArray("data"); //將data里面的內容轉成jsonObject JSONObject jsonTemp = new JSONObject(list_str); //得到answer里面的內容 JSONArray answer_obj = (JSONArray)jsonTemp.get("answer"); //log.info(answer_obj.get(0).toString()); //聲明一個list數組用于存放拼接answer里面的內容 List answerList = new ArrayList(); //拼接answer數組里面每一個內容變成一個["*","*","*"]格式的參數 for (int i=0; i){ JSONArray answer_arry = (JSONArray)answer_obj.get(i); //log.info(answer_arry.get(0).toString()); answerList.add("""+ answer_arry.get(0).toString() + """); } log.info(answerList.toString()); String trueAnswerList = answerList.toString(); vars.put("trueAnswerStr",trueAnswerList);
五、如何將從response得到的數據回寫到csv,并且可以追加
解決方案:在請求samper ,添加一個BeanShell PostProcessor
代碼:
String filePath = "D:/apache-jmeter-2.13/reportCodeData.csv";
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
String reportCode = vars.get("reportCode");
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath, true)));
out.write(reportCode +"
");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
解決方案:將參數提取出來然后判斷
代碼:"${topicFinished}"=="false"
例子:

七、使用正則處理response
解決方案:添加一個BeanShell Sampler,里面使用java代碼將提取出來的參數重新處理
代碼:
import java.util.regex.*;
import java.util.*;
String tempString = vars.get("SelectAnswer"); //SelectAnswer = "[["*"],["*"],["*"]]";
String[] array = tempString.split(",");
List templist = new ArrayList();
for(int i = 0; i < array.length; i++){
//正則雙引號中間的所有內容
String pattern = ""(.*?)"";
//創建Patten對象
Pattern r = Pattern.compile(pattern);
//創建mather對象
Matcher m = r.matcher(array[i]);
if(m.find()){
templist.add(m.group(0));
}
}
String exceptValue = templist.toString();//String exceptValue = "["*","*","*"]";
vars.put("newSelectAnswer",exceptValue);


