Jmeter中Bean Shell的使用(一)

一、什麼是Bean Shell

  • BeanShell是一種完全符合Java語法規範的腳本語言,並且又擁有自己的一些語法和方法;
  • BeanShell是一種鬆散類型的腳本語言(這點和JS類似);
  • BeanShell是用Java寫成的,一個小型的、免費的、可以下載的、嵌入式的Java源代碼解釋器,具有對象腳本語言特性,非常精簡的解釋器jar文件大小爲175k。
  • BeanShell執行標準Java語句和表達式,另外包括一些腳本命令和語法。

官網:http://www.BeanShell.org/

二、Jmeter有哪些Bean Shell

  • 定時器:  BeanShell Timer

  • 前置處理器:BeanShell PreProcessor

  • 採樣器:  BeanShell Sampler

  • 後置處理器:BeanShell PostProcessor

  • 斷言:   BeanShell斷言

  • 監聽器:  BeanShell Listener

 

三、BeanShell的用法

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

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

2、把jar包放到jmeter目錄\apache-jmeter-3.2\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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章