JMeter Complete Element Reference – Part II

In this article, we will discuss about  the next set of elements i.e Samplers, importance  of samplers, types of samplers  and their uasge  in our test. If you have missed the first part, click here

Samplers

Samplers perform the actual work of JMeter. Each sampler (except Test Action) generates one or more sample results. The sample results have various attributes (success/fail, elapsed time, data size etc) and can be viewed in the various listeners(will get to know in future posts 😛 ).

As we all know that Apache JMeter has ability to load and performance test many different server/protocol types such as HTTP, FTP, SOAP, LDAP, JDBC etc and we aslo know that Thread Group forms the base for simulating requests to the server.  Now we have problem here, how does a thread group knows which user request to make ? more over user request can be FTP request or HTTP request or SOAP request. The answer is quite simple Samplers, using samplers we can define what kind of request has to be simulated using JMeter.  Apache JMeter supports various types of samplers, lets go through each sampler in detail :

FTP Request Sampler

This sampler lets you send an FTP “retrieve file” or “upload file” request to an FTP server. If you are going to send multiple requests to the same FTP server, consider using a FTP Request Defaults Configuration Element so you do not have to enter the same information for each FTP Request Generative Controller. When downloading a file, it can be stored on disk (Local File) or in the Response Data, or both.

As you can notice from the above screenshot, we are trying to download “Test.txt” file by sending an FTP request to ftp.example.com. In order to upload a file into the server, we just to select put(STOR) radio button that’s it !! a file will be uploaded .

JDBC Request Sampler

This sampler lets you execute Database Performance Testing. It sends a JDBC Request (an SQL query) to a database.

For example, a database server has a field test_result stored in a table name test_tbl. You want to query this data from the database server; you can configure JMeter to send a SQL query to this server to retrieve data.

Note: Before using this you need to set up a JDBC Connection Configuration Configuration element. In this element we will  provide all the database details to establish a connection with the DB.

BeanShell Sampler

This sampler allows you to write a sampler using the BeanShell scripting language.

For full details on using BeanShell, please see the BeanShell website.

The test element supports the ThreadListener and TestListener interface methods. These must be defined in the initialisation file. See the file BeanShellListeners.bshrc for example definitions.

From JMeter version 2.5.1, the BeanShell sampler also supports the Interruptible interface. The interrupt() method can be defined in the script or the init file.

Control Panel

Parameters

Attribute Description Required
Name Descriptive name for this sampler that is shown in the tree. The name is stored in the script variable Label No
Reset bsh.Interpreter before each call If this option is selected, then the interpreter will be recreated for each sample. This may be necessary for some long running scripts. For further information, see Best Practices – BeanShell scripting . Yes
Parameters Parameters to pass to the BeanShell script. This is intended for use with script files; for scripts defined in the GUI, you can use whatever variable and function references you need within the script itself. The parameters are stored in the following variables:

  • Parameters – string containing the parameters as a single variable
  • bsh.args – String array containing parameters, split on white-space
No
Script file A file containing the BeanShell script to run. The file name is stored in the script variable FileName No
Script The BeanShell script to run. The return value (if not null) is stored as the sampler result. Yes (unless script file is provided)

N.B. Each Sampler instance has its own BeanShell interpeter, and Samplers are only called from a single thread

If the property “beanshell.sampler.init” is defined, it is passed to the Interpreter as the name of a sourced file. This can be used to define common methods and variables. There is a sample init file in the bin directory: BeanShellSampler.bshrc.

If a script file is supplied, that will be used, otherwise the script will be used.

JMeter processes function and variable references before passing the script field to the interpreter, so the references will only be resolved once. Variable and function references in script files will be passed verbatim to the interpreter, which is likely to cause a syntax error. In order to use runtime variables, please use the appropriate props methods, e.g. props.get(“START.HMS”); props.put(“PROP1″,”1234”);
BeanShell does not currently support Java 5 syntax such as generics and the enhanced for loop.

Before invoking the script, some variables are set up in the BeanShell interpreter:

The contents of the Parameters field is put into the variable “Parameters”. The string is also split into separate tokens using a single space as the separator, and the resulting list is stored in the String array bsh.args.

The full list of BeanShell variables that is set up is as follows:

  • log – the Logger
  • Label – the Sampler label
  • FileName – the file name, if any
  • Parameters – text from the Parameters field
  • bsh.args – the parameters, split as described above
  • SampleResult – pointer to the current SampleResult
  • ResponseCode = 200
  • ResponseMessage = “OK”
  • IsSuccess = true
  • ctx – JMeterContext
  • vars – JMeterVariables – e.g. vars.get(“VAR1”); vars.put(“VAR2″,”value”); vars.remove(“VAR3”); vars.putObject(“OBJ1”,new Object());
  • props – JMeterProperties (class java.util.Properties)- e.g. props.get(“START.HMS”); props.put(“PROP1″,”1234”);

When the script completes, control is returned to the Sampler, and it copies the contents of the following script variables into the corresponding variables in the SampleResult :

  • ResponseCode – for example 200
  • ResponseMessage – for example “OK”
  • IsSuccess – true/false

The SampleResult ResponseData is set from the return value of the script. Since version 2.1.2, if the script returns null, it can set the response directly, by using the method SampleResult.setResponseData(data), where data is either a String or a byte array. The data type defaults to “text”, but can be set to binary by using the method SampleResult.setDataType(SampleResult.BINARY).

The SampleResult variable gives the script full access to all the fields and methods in the SampleResult. For example, the script has access to the methods setStopThread(boolean) and setStopTest(boolean). Here is a simple (not very useful!) example script:

if (bsh.args[0].equalsIgnoreCase("StopThread")) {
    log.info("Stop Thread detected!");
    SampleResult.setStopThread(true);
}
return "Data from sample with Label "+Label;
//or, since version 2.1.2
SampleResult.setResponseData("My data");
return null;

Another example:
ensure that the property beanshell.sampler.init=BeanShellSampler.bshrc is defined in jmeter.properties. The following script will show the values of all the variables in the ResponseData field:

return getVariables();

For details on the methods available for the various classes ( JMeterVariables SampleResult etc) please check the Javadoc or the source code. Beware however that misuse of any methods can cause subtle faults that may be difficult to find .

BSF Sampler:

This sampler allows you to write a sampler using a BSF scripting language.

Here is an example of BSF  Sampler in JMeter

Access Log Sampler:

AccessLogSampler was designed to read access logs and generate http requests. For those not familiar with the access log, it is the log the webserver maintains of every request it accepted. This means every image, css file, javascript file, html file..

SMTP Sampler:

The SMTP Sampler can send mail messages using SMTP/SMTPS protocol. It is possible to set security propocols for the connection (SSL and TLS), as well as user authentication. If a security protocol is used a verification on the server certificate will occur.
Two alternatives to handle this verification are available:

  • Trust all certificates. This will ignore certificate chain verification
  • Use a local truststore. With this option the certificate chain will be validated against the local truststore file.

JUnit Request Sampler

The current implementation supports standard Junit convention and extensions. It also includes extensions like oneTimeSetUp and oneTimeTearDown. The sampler works like the JavaSampler with some differences.
1. rather than use Jmeter’s test interface, it scans the jar files for classes extending junit’s TestCase class. That includes any class or subclass.
2. Junit test jar files should be placed in jmeter/lib/junit instead of /lib directory. In versions of JMeter after 2.3.1, you can also use the “user.classpath” property to specify where to look for TestCase classes.
3. Junit sampler does not use name/value pairs for configuration like the JavaSampler. The sampler assumes setUp and tearDown will configure the test correctly.
4. The sampler measures the elapsed time only for the test method and does not include setUp and tearDown.
5. Each time the test method is called, Jmeter will pass the result to the listeners.
6. Support for oneTimeSetUp and oneTimeTearDown is done as a method. Since Jmeter is multi-threaded, we cannot call oneTimeSetUp/oneTimeTearDown the same way Maven does it.
7. The sampler reports unexpected exceptions as errors. There are some important differences between standard JUnit test runners and JMeter’s implementation. Rather than make a new instance of the class for each test, JMeter creates 1 instance per sampler and reuses it. This can be changed with checkbox “Create a new instance per sample”.
The current implementation of the sampler will try to create an instance using the string constructor first. If the test class does not declare a string constructor, the sampler will look for an empty constructor. Example below:

Empty Constructor:
public class myTestCase {
public myTestCase() {}
}

String Constructor:
public class myTestCase {
public myTestCase(String text) {
super(text);
}
}
By default, Jmeter will provide some default values for the success/failure code and message. Users should define a set of unique success and failure codes and use them uniformly across all tests.
General Guidelines
If you use setUp and tearDown, make sure the methods are declared public. If you do not, the test may not run properly.
Here are some general guidelines for writing Junit tests so they work well with Jmeter. Since Jmeter runs multi-threaded, it is important to keep certain things in mind.

1. Write the setUp and tearDown methods so they are thread safe. This generally means avoid using static memebers.
2. Make the test methods discrete units of work and not long sequences of actions. By keeping the test method to a descrete operation, it makes it easier to combine test methods to create new test plans.
3. Avoid making test methods depend on each other. Since Jmeter allows arbitrary sequencing of test methods, the runtime behavior is different than the default Junit behavior.
4. If a test method is configurable, be careful about where the properties are stored. Reading the properties from the Jar file is recommended.
5. Each sampler creates an instance of the test class, so write your test so the setup happens in oneTimeSetUp and oneTimeTearDown.

                                                                           

The following JUnit4 annotations are recognised:

  • @Test – used to find test methods and classes. The “expected” and “timeout” attributes are supported.
  • @Before – treated the same as setUp() in JUnit3
  • @After – treated the same as tearDown() in JUnit3
  • @BeforeClass, @AfterClass – treated as test methods so they can be run independently as required

Note that JMeter currently runs the test methods directly, rather than leaving it to JUnit. This is to allow the setUp/tearDown methods to be excluded from the sample time.

There are many more samplers that JMeter can support. Click here for more details.

If you enjoy reading article then you can subscribe our updates for FREE, just add your email id . I will keep on updating the article for latest testing information. Subscribe and stay tuned for updates, there’s lot more to come.

🙂 Happy Performance Testing !! 🙂

Advertisements

4 thoughts on “JMeter Complete Element Reference – Part II

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s