BeanShell是最早进的JMeter内置组件之一。JMeter具备丰富的内置插件,可知足性能测试的许多需求。例如,在编写一些复杂的测试时,您可能须要一些额外的脚本。在这种状况下,值得使用Beanshell。在这篇文章中,咱们将讨论使用JMeter Beanshell和常见用例测试复杂逻辑。Beanshell具备运行Java代码的功能,而且能够访问JMeter API和在JMeter类路径中加载的外部类。html
JMeter具备如下启用Beanshell的组件:java
如下是向Beanshell公开的JMeter API类。若是查看Beanshell的底部,您将看到为脚本定义的变量列表。web
您能够在Beanshell中访问
SampleResult类的成员变量和方法。shell
例如,您能够分别使用setThreadName()
和getThreadName()
方法设置和获取线程名称。apache
此类容许您手动设置响应代码。在某些状况下,您可能须要根据从服务器得到的响应来设置响应代码。
这是一个用例示例:api
if(condition){ ResponseCode =“200”; } else { ResponseCode =“500”; }
此类容许您手动设置响应消息。示例用例与for的用例相同ResponseCode
。服务器
IsSuccess
是Boolean
反映采样器是否成功的反映。若是设置为true,则认为采样器已“经过”。不然,它将被标记为“失败”。app
if(condition){ IsSuccess = true; } else { IsSuccess = false; }
ctx
是暴露给BeanShell的最强大的变量。它表明
JMeterContext类,它自己就是JMeter。它提供对底层JMeter引擎,采样器及其结果以及变量/属性的读/写访问。ide
如下代码演示了ctx变量的用法:函数
log.info(“Current Sampler class is:”+ ctx.getCurrentSampler()); log.info(“JMeter Engine类是:”+ ctx.getEngine()); log.info(“上一个响应消息是:”+ ctx.getPreviousResult()。getResponseMessage()); log.info(“上一个响应代码是:”+ ctx.getPreviousResult()。getResponseCode()); log.info(“Previous Response URL is:”+ ctx.getPreviousResult()。getURL()); log.info(“Previous Response Time is:”+ ctx.getPreviousResult()。getTime()); log.info(“Previous Domain is:”+ ctx.getPreviousSampler()。getDomain()); log.info(“Previous Protocol is:”+ ctx.getPreviousSampler()。getProtocol()); log.info(“Previous Port is:”+ ctx.getPreviousSampler()。getPort()); log.info(“Previous Method is:”+ ctx.getPreviousSampler()。getMethod()); log.info(“Thread Name is:”+ ctx.getThread()。getThreadName()); log.info(“Thread Start Time is:”+ ctx.getThread()。getStartTime()); log.info(“Thread End Time is:”+ ctx.getThread()。getEndTime()); log.info(“在错误时启动下一个线程循环:”+ ctx.getThreadGroup()。getOnErrorStartNextLoop()); log.info(“Stop Test on Error:”+ ctx.getThreadGroup()。getOnErrorStopTest());
另外一个用例是,若是要将全部断言错误写入HTML文件,以即可以查看哪一个断言不起做用。您能够ctx
在Beanshell断言中使用变量来遍历当前上下文中的全部采样器,并将失败写入html文件中。
添加Beanshell断言并复制如下代码以将全部断言写入html文件:
import org.apache.jmeter.services.FileServer; f = new FileOutputStream(“C:\\ apache-jmeter-4.0 \\ bin \\ result.html”,true); pt = new PrintStream(f); pt.println( “<HTML> <BODY>”); for(a:SampleResult.getAssertionResults()){ if(a.isError()|| a.isFailure()){ log.error(“URL:”+ ctx.getCurrentSampler()。toString()); log.error(Thread.currentThread()。getName()+“:”+ SampleLabel +“:响应失败:”+ new String((byte [])ResponseData)); pt.println(“URL:”+ ctx.getCurrentSampler()。toString()); pt.println(Thread.currentThread()。getName()+“:”+ SampleLabel +“:响应断言失败:”+ new String((byte [])ResponseData)); pt.println( “</ BODY> </ HTML>”); pt.close(); f.close(); }
它是
JMeterVariables类的一个实例,提供对当前变量的读/写访问,可以枚举/更改现有变量,建立新变量以及获取嵌套属性。全部JMeter变量都是Java字符串。若是您须要将其余内容添加到JMeter变量中,则须要先将其强制转换为字符串。如下代码段演示了如何将之前的采样器响应数据保存到JMeter变量中:
vars.put(“ResponceData”,prev.getResponseDataAsString()); log.info(vars.get( “ResponceData”));
基本上,这与vars
它相同,但它公开了JMeter属性。有关java.util.Properties
更多信息,请参阅有关JMeter属性的JavaDoc on 和JMeter文档。的主要区别之间props
而且vars
是道具备一个“全局”范围,而范围vars
是有限的,以当前线程组。
log
表示Logger
类,可用于将消息附加到jmeter.log
文件中。如下是示例用例:
log.info(“使用INFO级别测试消息”); log.error(“使用ERROR级别测试消息”);
在某些状况下,您可能但愿根据响应添加参数。您能够使用Beanshell预处理器执行此操做。
该sampler.addArgument()
方法容许您在手动访问服务器以前添加参数。
如前所述,您能够使用Beanshell动态更新JMeter变量。假设您有一个名为“counter”的用户定义变量,其值为“1”。假设您但愿每次在while循环中执行采样器时将此计数器值递增1。如下代码段将计数器值递增1并更新相同的值:
int counter = Integer.parseInt(vars.get(“counter”))+ 1; vars.put( “计数器”,Integer.toString(计数器));
假设您须要调用用户建立的类中存在的方法之一。您能够使用Beanshell调用用户建立的JAR文件中存在的方法。
lib/ext
JMeter的文件夹中。例如 :
鉴于您有如下课程:
package timeStampPack; import java.text.SimpleDateFormat; import java.util.Calendar; public class TimeStampConversion { public TimeStampConversion(){} public static String getTimeStamps(int count) { String dates =“”; for(int i = 1; i <= count; i ++) { try { Thread.sleep(1L); } catch(InterruptedException e){ e.printStackTrace(); } dates = dates +“TimeStamp”+ i +“==>”+ getCurrentDateTime()+“\ n”; } 返回日期; } }
在上面的类中,getTimeStamps()
方法返回timestamp,将其打包为timeStamp.jar并将文件复制到lib/ext
JMeter安装的文件夹中。
将Beanshell Sampler添加到测试计划中,并将如下代码放入“脚本”区域。
导入timeStampPack。*; var time = TimeStampConversion.getTimeStamps(1); log.info(时间);
上面的代码将调用getTimeStamps()
方法并记录该值。
您还能够使用Beanshell使用CSV文件参数化测试数据。查看此文章以查看详细信息。
JMeter是数千名开发人员使用的优秀开源负载测试工具。若是您是其中之一,则可能须要加载测试。JMeter可用于负载测试。使用RedLine13,您能够在10分钟内使用任何移动应用程序,Web应用程序或API的JMX脚本运行JMeter负载测试。
BeanShell is one of the most advanced JMeter built-in components. JMeter has rich built-in plugins which cover many needs of a performance test. For example, you might need some additional scripting while writing some complex tests. In such cases, it’s worth using Beanshell. In this post, we are going to be talking about testing complex logic with JMeter Beanshell and common use cases. Beanshell has the functionality to run java code and has access to JMeter APIs and external classes that are loaded in the JMeter classpath.
JMeter has the following Beanshell enabled components:
Beanshell Sampler.
Beanshell PreProcessor.
Beanshell PostProcessor.
__BeanShell function.
Beanshell Assertion.Below are the JMeter API classes exposed to Beanshell. If you look at the bottom of Beanshell, you’ll see the list of variables defined for the script.
You can access the member variables and methods of the
SampleResult Class in Beanshell.
For example, you can set and get the thread name using setThreadName()
and getThreadName()
methods respectively.
This class allows you to set response code manually. In some situations, you may need to set the response code based on the response that you get from server.
Here is a sample use-case:
if (condition) { ResponseCode = "200"; } else { ResponseCode = "500"; }
This class allows you to set the response message manually. The sample use case is the same as the one for ResponseCode
.
IsSuccess
is a Boolean
that reflects whether the sampler succeeded. If it’s set to true, the sampler is considered to have “passed.” Otherwise, it will be marked as “failed”.
if (condition) { IsSuccess = true; } else { IsSuccess = false; }
ctx
is the most powerful variable exposed to BeanShell. It represents the
JMeterContext class, which is virtually JMeter itself. It provides read/write access to the underlying JMeter engine, samplers, and their results as well as variables/properties.
The following code demonstrates the usage of ctx variable:
log.info("Current Sampler class is: " + ctx.getCurrentSampler()); log.info("JMeter Engine class is: " + ctx.getEngine()); log.info("Previous Response Message is: " + ctx.getPreviousResult().getResponseMessage()); log.info("Previous Response Code is: " + ctx.getPreviousResult().getResponseCode()); log.info("Previous Response URL is: " + ctx.getPreviousResult().getURL()); log.info("Previous Response Time is: " + ctx.getPreviousResult().getTime()); log.info("Previous Domain is: " + ctx.getPreviousSampler().getDomain()); log.info("Previous Protocol is: " + ctx.getPreviousSampler().getProtocol()); log.info("Previous Port is: " + ctx.getPreviousSampler().getPort()); log.info("Previous Method is: " + ctx.getPreviousSampler().getMethod()); log.info("Thread Name is: " + ctx.getThread().getThreadName()); log.info("Thread Start Time is: " + ctx.getThread().getStartTime()); log.info("Thread End Time is: " + ctx.getThread().getEndTime()); log.info("Start Next Thread Loop on Error: " + ctx.getThreadGroup().getOnErrorStartNextLoop()); log.info("Stop Test on Error: " + ctx.getThreadGroup().getOnErrorStopTest());
Another use case is if you want to write all Assertions error to an HTML file so you can see which assertion is not working. You can use ctx
variable in Beanshell assertion to iterate through all samplers in the current context and write the failures in an html file.
Add a Beanshell assertion and copy the following code to write all the assertions to a html file:
import org.apache.jmeter.services.FileServer; f = new FileOutputStream("C:\\apache-jmeter-4.0\\bin\\result.html", true); pt = new PrintStream(f); pt.println("<html><body>"); for (a: SampleResult.getAssertionResults()) { if (a.isError() || a.isFailure()) { log.error("URL :"+ ctx.getCurrentSampler().toString()); log.error(Thread.currentThread().getName()+": "+SampleLabel+": Assertion failed for response: " + new String((byte[]) ResponseData)); pt.println("URL :"+ ctx.getCurrentSampler().toString()); pt.println(Thread.currentThread().getName()+": "+SampleLabel+": Assertion failed for response: " + new String((byte[]) ResponseData)); // update here what you want to write } pt.println("</body></html>"); pt.close(); f.close(); }
It’s an instance of the
JMeterVariables class and provides read/write access to current variables, is capable of enumerating/changing existing variables, creating new variables, and obtaining nested properties. All JMeter variables are Java strings. If you need to put something else to a JMeter variable, you’ll need to cast it to a string first. The following code snippet demonstrates how to save previous sampler response data into a JMeter variable:
vars.put("ResponceData", prev.getResponseDataAsString()); log.info(vars.get("ResponceData"));
Basically, this is the same as vars
, but it exposes JMeter properties instead. See JavaDoc on java.util.Properties
and JMeter documentation on JMeter properties for more information. The primary distinction between props
and vars
is that props have a “global” scope, whereas the scope of vars
is limited to the current thread group.
log
represents the Logger
class and can be used to append a message into jmeter.log
file. The following is the sample use case:
log.info("Test Message with INFO level"); log.error("Test Message with ERROR level");
In some cases, you might want to add parameters based on the response. You can do this using the Beanshell preprocessor.
The sampler.addArgument()
method allows you to add arguments before hitting the server manually.
As mentioned earlier, you can update JMeter variables on the fly using Beanshell. Assume that you have a user defined variable called “counter” with the value of “1”. Let’s say you want to increment this counter value by one every time it executes a sampler in while loop. The following code snippet increments the counter value by one and updates the same:
int counter = Integer.parseInt(vars.get("counter")) +1; vars.put("counter",Integer.toString(counter));
Assume that you have a requirement to call one of the methods which is present in a user created class. You can call the methods present in user created JAR file using Beanshell.
lib/ext
folder of JMeter.For Example :
Given you have the following class:
package timeStampPack; import java.text.SimpleDateFormat; import java.util.Calendar; public class TimeStampConversion { public TimeStampConversion() {} public static String getTimeStamps(int count) { String dates = ""; for (int i = 1; i <= count; i++) { try { Thread.sleep(1L); } catch (InterruptedException e) { e.printStackTrace(); } dates = dates + "TimeStamp" + i + "==>" + getCurrentDateTime() + "\n"; } return dates; } }
In above class, getTimeStamps()
method returns timestamp, packages it as timeStamp.jar and copies the file to the lib/ext
folder of your JMeter installation.
Add Beanshell Sampler to your Test Plan and put the following code into the “Script” area.
Import timeStampPack.*; var time=TimeStampConversion.getTimeStamps(1); log.info(time);
The above code will call getTimeStamps()
method and logs the value.
You can also use Beanshell to parameterize test data using CSV file. Check this article to see details.
JMeter is an excellent open source load testing tool used by thousands of developers. If you’re one of them, you may want to load test. JMeter can be used for load testing. With RedLine13, you can run a JMeter Load Test with your JMX script of any mobile application, web application, or API in 10 minutes.