Over a million developers have joined DZone.

Groovy Templates Cheat Sheet for JMeter

DZone's Guide to

Groovy Templates Cheat Sheet for JMeter

Need help with your Groovy templates? Check out this cheat sheet to help you get started with scripting in Apache JMeter.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

In this article, we will discuss the most common uses of Groovy scripting in Apache JMeter load testing scripts and show you how to create them. You can use the Groovy templates shown here in your JMeter performance testing scripts.

We will cover the following situations:

  • Debugging
  • Transferring data and objects
  • Working with files
  • Working with time

Why Use Groovy in JMeter?

Briefly, Groovy is one of the languages that implements a Compilable Interface, so it's great for performing complex calculations because the script will only need to be compiled once for all threads and loops, and we will no longer need to spend resources on this. You can read more about that in articles that are devoted to the performance research of BeanShell, JSR223 and Java code:

More Groovy advantages include:

  • You write less lines of code than when you write code on java.
  • This is the only language that is supported out of the box and implements a compilable interface.
  • You can use Groovy in any sampler using the JMeter Function __groovy().

Groovy Resources

Here are some resources you can use to get acquainted with the peculiarities of Groovy. We recommend spending some time on them. It will be worth it because you will see that writing your scripts becomes much faster and easier.

Groovy Scripting Templates

You can use Groovy in four JMeter elements: JSR223 Sampler, JSR223 Postprocessor, JSR223 Preprocessor, and JSR223 Assertion. Besides, you can use small Groovy scripts in any another element using __groovy() JMeter Function.

Let’s get started with the templates and examples.

Debugging With Groovy

Sometimes you need to see the values of JMeter variables or properties from different places in the load script or in complex Groovy scripts.

Groovy enables you to:

  • Output information to the system console and the JMeter console
  • Get JMeter variables and properties with the  vars.get() props.get()   functions;
  • Mark messages with an error indicator as errors in the log file.
//print to the system console
OUT. println 'Output to system console'
//print to jmeter console
log.info 'Output to jmeter console with info tracker'
log.error 'Output to jmeter console as error'
//way to get var
log.warn 'Output to jmeter ${var} console'
log.warn 'Output to jmeter console' + vars.get("var")            

Increase imagegroovy scripting templates

Transferring Data and Objects (like List, Maps, Array etc.) Between Samplers and Threads

Sometimes, you need to save a value to use it later in the sampler, or use massive values in another JSR223 Postprocessor to compare a newly received value with values in the array. For instance, in one example of this article, we check the appearance of new parts of the video in the HLS playlist.

Groovy enables you to:

  • Use  vars.put() ,  vars.get() to get and set JMeter variables inside one thread;
  • Use  vars.putObject() vars.getObject() to get and set any objects, like lists and maps, inside the thread;
  • Use props.put()  , props.get() to get and set JMeter variables between threads. You can also get the property via the JMeter  function __property () ;
//list of parts
List<String> historyList = new ArrayList()
// the list filling 
for (def i = 0; i < count; i++) {
historyList.add(vars.get("chunks_" + (i+1)))
//just checking for debugging
log.info String.join( ",", historyList ))
//put to variable
vars.putObject("historyList", historyList)

//get the list in another jsr element 
List<String> historyList = vars.getObject("historyList")            

  • To transfer objects between samplers and threads, the BeanShell  sampler has bash.env  (something like a global namespace), but JSR223 does not have such a thing. You can solve this problem by writing your own wrapper for  ConcurrencyHashedMap. We covered the principle of the work of the wrapper here.

Result Modification

 vars.get() returns a string, even if the value of the variable is a number. vars.put() also takes a string value, so do not forget to convert them from string and to string.

//concat with new part
def var1 = vars.get(‘firstVar’)
var1 =+ ‘ upd’
vars.put(‘firstVar’, var1)

//string to int convert
def number = (Integer)'1'
def number = '1'.toInteger()
def number = '1' as Integer

//int to string convert
def strNumber = number.toString();

Data Array Modification

You might encounter a situation where you extract a certain group of values using an extractor with MatchNo = -1. Then, you need to do something with them. For example, combine them into one big string for the next request. In the example below, we get all values that were retrieved using the RegEx extractor and concatenating them.

// This code is needed to generate a dynamic body for the POST request. 
// UserIds - variable from Regexp extractor
def result = ""
def count = Integer.parseInt(vars.get("UserIds_matchNr"))
for (def i = 0; i < count; i++) {
def block = vars.get("UserIds_" + (i+1) )
result += "\"" + block + "\""
if (i != count - 1) { // It's necessary so that the last block does not end with the symbol ","
result += ",\n"}}
vars.put("UserIds", result)

Working With Files

JMeter has an element for reading CSV files, the CSV data set config. But, sometimes, this is not enough. Maybe your file has a different format, or you want to build a new file. Working with files in Groovy is not difficult. It requires writing literally a couple of lines. Writing and reading are performed in one line. You can also read from a file using filters.

Note: a string in single quotes is a Groovy string, a string in double quotes is a Java string.

// Сreate file
def file1 = new File('groovy1.txt')

// Writing to the file  using write method
file1.write 'Working with files the Groovy way is easy.\n'

// Reading contents of files to an array
def lines = file1.readLines()
// Groovy assert
assert 'Working with files the Groovy way is easy.' == lines[0]

// We can also read content with a filter
sw = new StringWriter()
file1.filterLine(sw) { it =~ /Groovy/ }
assert 'Working with files the Groovy way is easy.\r\n' == sw.toString()

XML parsing is not difficult as well:

String xml = “
 <action type=”error” info=”itsErrors”/>
 <action type="warning" info=”warnWarn”/>
 <action type=”info” info=”justLogInfo”/>

XmlParser parser = new XmlParser()
def actions= parser.parseText (xml)
actions.action.each { action ->
    println "${action.'@type'}: ${action.'@info'}";

Working With Time

We often work with dates and time, because such information is often used in various requests, for example, setting the expiration date of the subscription (future time) or the time of the event that is important for the test (future time, but no more than half an hour). This entire article is devoted to this topic. Here are some examples:

def date = new Date()
// current date in epoch time
println date.getTime() / 1000 

date = new Date().parse('yyyy/MM/dd', '1973/07/09')

dateNext = date.clone()
datePrevious = date.clone()
// date + 1 day
// date + 1 day too

assert dateNext == date // date comparison

def timeZoneDate = aDate.format("EEEE, MMMM dd, yyyy, hh:mm a '('zzz')'", TimeZone.getTimeZone("EST5EDT")) // get date for specific timezone

The Groovy Function

As we said before, Groovy doesn’t have to be used only in JSR223. JMeter has a built-in function __groovy(), which allows you to execute Groovy code in any field. For instance, the code below takes the current time of the system, adds 5 minutes to it and returns a string with a new value.

${__groovy(use(groovy.time.TimeCategory) { (new Date() + 5.minutes).format('HH:mm') })}

Read more about Groovy functions here.

This is the most common use of scripting in JMeter scripts that we have been able to allocate. If you have use Groovy for other uses, please share in the comments.

Want to learn more? View this free webinar: Advanced JMeter Scripting - Writing Assertions in Groovy.

Running Your JMeter Scripts in BlazeMeter

After creating your JMeter scripts, you can massively scale your tests with BlazeMeter. To try BlazeMeter out, put your URL in the box below, and your test will start in minutes. BlazeMeter also enables you to collaborate on your tests and reports, drill down into labels for advanced analysis and compare results over time.

Increase imagerunning groovy in jmeter

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

java ,groovy ,jmeter ,scripting templates ,apache ,debugging

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}