最近開始使用jmeter做接口測試,遇到的主要問題在這里記錄一下。
測試場景:
線程組1-登錄-P1接口用例
線程組2-登錄-P2接口用例
如果線程組1和2用同一個用戶登錄,線程組2用例執行會提示用戶登錄超時相關信息,這個時候就要考慮線程組1中的參數codeKey和loginCode能在線程組2中使用就解決問題了,另外一種沒辦法的辦法就是用2個賬號登陸,這樣設置的全局變量數據不能共用了,也很麻煩。
1.線程組1中的參數保存到文件中,線程組2通過讀取文件中的數據實現數據共享
線程組1登錄用例添加后置處理器beanshell postprocessor。腳本內容如下:
String filePath = System.getProperty("user.dir") + "\\loginMsg.txt";
vars.put("filePath",filePath);
File file = new File(filePath);
try {
if (file.exists()){
file.delete();
}
file.createNewFile();
FileWriter fs = new FileWriter(filePath,true);
BufferedWriter bw = new BufferedWriter(fs);
bw.write(vars.get("codeKey")+"?");
bw.write(vars.get("loginCode"));
bw.write(System.getProperty("line.separator"));
fs.flush();
bw.close();
fs.close();
}catch(IOException e) {
e.printStackTrace();
}
線程組2中通過csv數據文件設置讀取文件中的數據,這個也可以實現,但個人覺得沒必要這么麻煩。
2.通過函數助手__setProperty和后置處理器beanshell postprocessor實現跨線程參數共享
登錄參數codeKey和loginCode

就是把通過正則獲取到的${codeKey}值設置為全局變量,並以新的名字newcodeKey來引用

在登錄請求添加后置處理器beanshell postprocessor

這樣codeKey和loginCode就已經設置為全局變量了。發現用setProperty log中會報錯顯示變量未定義:ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``${codeKey}; ${loginCode} : Attempt to access property on undefined variable or class name
WARN o.a.j.e.BeanShellPostProcessor: Problem in BeanShell script: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``${codeKey}; ${loginCode} : Attempt to access property on undefined variable or class name
使用vars和props定義beanshell變量沒問題,具體什么原因導致的,還不太清楚,有時間再研究一下。
props.put("newCodeKey",vars.get("CodeKey"));
props.put("newLoginCode",vars.get("LoginCode"));
線程組2中使用__P函數來調用以上參數:

這樣就實現了多線程組共用同一賬號登陸的場景。
避免線程組間用例執行順序雜亂無章,在測試計划中勾選“獨立運行每個線程組”:

