July 15, 2021

The Groovy Templates Cheat Sheet for JMeter

Open Source Automation

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.

Table of Contents:


What Are Groovy Templates?

Groovy templates are a templating engine for JavaScript, which are used for JMeter.

First, let's cover some basics of Groovy and JMeter. Then, we'll delve into Groovy templates.

Why Use Groovy in JMeter?

Briefly, Groovy is one of the languages that implement 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().


How to Use Groovy 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")


groovy 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 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 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 in this BlazeMeter blog.

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 partdef var1 = vars.get(firstVar)
var1 =+  upd
vars.put(firstVar, var1)

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

//int to string convertdef 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, and 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 extractordef 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 also 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 filedef 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 arraydef lines = file1.readLines()
// Groovy assertassert'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 = 

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

Working with Time

We also 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. 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 daydateNext++  // date + 1 day toodateNext.next() assert dateNext == date // date comparisondef 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.

Groovy Templates + JMeter + 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. Request a live demo from one of our performance engineers today.

running groovy in jmeter




Related Resources