jmeter Bean Shell的使用(二)


BeanShell的用法

   在此介紹下BeanShell PreProcessor的用法,其它的beahshell可以類推。在此我們使用beahshell調用自己寫的工具類,工具類實現了密碼的加、解密功能:

1、在eclipse寫好代碼,然后把該類打成jar包(在類上點擊右鍵->Export->jar file)

2、把jar包放到jmeter目錄\apache-jmeter-2.13\lib\ext下

3、打開jmeter,添加一個http sampler(調用登錄接口),在sampler下添加一個BeanShell PreProcessor

4、在beanshell PreProcessor中導入我們的jar包,調用里面的加、解密碼方法,把結果保存在jmeter變量中,下面兩個方法是beanshell中我們最常用到的:

  • vars.get(String paramStr):獲得變量值
  • vars.put(String key,String value):,將數據存到jmeter變量中

復制代碼
import com.pingan.ff.account.user.utils.*;

//加密
System.out.println("*****加密*****");
String password = "123123";
String encode = SecurityUtils.getKey(password);//調用工具類中的方法進行加密
System.out.println("Set my encode");
vars.put("encode",encode);//把值保存到jmeter變量encode中
String getEncode=vars.get("encode");
System.out.println("Get my encode: " + getEncode);
復制代碼

5、把加密后的密碼存到jmeter變量中,然后在http sampler中就可以通過${encode}進行使用了:

6、執行腳本:

 

四、Bean Shell常用內置變量

    JMeter在它的BeanShell中內置了變量,用戶可以通過這些變量與JMeter進行交互,其中主要的變量及其使用方法如下:

  • log:寫入信息到jmeber.log文件,使用方法:log.info(“This is log info!”);

  • ctx:該變量引用了當前線程的上下文,使用方法可參考:org.apache.jmeter.threads.JMeterContext

  • vars - (JMeterVariables):操作jmeter變量,這個變量實際引用了JMeter線程中的局部變量容器(本質上是Map),它是測試用例與BeanShell交互的橋梁,常用方法:

    a) vars.get(String key):從jmeter中獲得變量值

    b) vars.put(String key,String value):數據存到jmeter變量中

    更多方法可參考:org.apache.jmeter.threads.JMeterVariables

  • props - (JMeterProperties - class java.util.Properties):操作jmeter屬性,該變量引用了JMeter的配置信息,可以獲取Jmeter的屬性,它的使用方法與vars類似,但是只能put進去String類型的值,而不能是一個對象。對應於java.util.Properties。 

    a) props.get("START.HMS");  注:START.HMS為屬性名,在文件jmeter.properties中定義 

    b) props.put("PROP1","1234"); 

  • prev - (SampleResult):獲取前面的sample返回的信息,常用方法:

    a) getResponseDataAsString():獲取響應信息

    b) getResponseCode() :獲取響應code

    更多方法可參考:org.apache.jmeter.samplers.SampleResult

  • sampler - (Sampler):gives access to the current sampler

 

 

操作變量:通過使用Bean shell內置對象vars可以對變量進行存取操作

    a) vars.get("name"):從jmeter中獲得變量值

    b) vars.put("key","value"):數據存到jmeter變量中

操作屬性:通過使用Bean shell內置對象props 可以對屬性進行存取操作

    a) props.get("START.HMS");  注:START.HMS為屬性名,在文件jmeter.properties中定義 

    b) props.put("PROP1","1234");

 

引用外部Jar包:

  上面四、五介紹了如何引用外部java和class文件,如果文件比較多時我們可以把它們打成一個jar包然后在jemter中調用,具體如何使用可以看我上一篇有介紹:Jmeter之Bean shell使用(一)

  在這里想補充一點的是jmeter中引入jar的方法:

  1、上一篇中已使用過的:把jar包放到jmeter目錄\apache-jmeter-2.13\lib\ext下

  2、在Test Plan的右側面板最下方直接添加需要引用的jar包,如下圖:

 

七、其它用法: 

1、在Test Plan中定義如下三個變量:

2、Bean Shell可腳本如下:

  a、bean shell可以接受傳入參數,如下圖:${u1} ${u2} ${u3}

  b、參數可以通過bsh.args[]按順序提取

  c、bean shell提供了一個內置變量Parameters,來保存參數的集合

3、運行結果:

下圖中1輸入的這兩句設置:

ResponseCode = 500;
ResponseMessage = "This is a test";

下圖中2輸入的這兩句設置:

log.info(Parameters);

log.info(Label);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM