Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Test Plans and Samplers

JSR223 and Groovy Scripting in JMeter

Script JMeter with JSR223 elements and Groovy: the vars, props, prev, sampler and log objects, pre- and post-processors, assertions, compilation caching and what to avoid.

JMeter's built-in elements cover most needs, but sooner or later you need logic they do not offer: building a signature, parsing an odd response, computing a value from three variables. For that, JMeter has JSR223 elements that run a script in a language such as Groovy. Groovy is the recommended choice: it is close to Java, fast when cached and shipped with JMeter.

Honesty note. JMeter and Groovy cannot run here. The Groovy code is shown read-only and is written from the documented API. The runnable blocks are JavaScript stand-ins that mimic the vars, props and prev objects so you can practise the logic; the Groovy lines are not executed.

Where scripts can live

All of these exist in a JSR223 flavour (choose Language: groovy):

Element Runs Typical use
JSR223 Sampler As a request Custom protocol call, calculation with a timed result
JSR223 PreProcessor Before a sampler Build a body, compute a signature or timestamp
JSR223 PostProcessor After a sampler Parse a response, set variables
JSR223 Assertion After post-processors Custom check; set failure
JSR223 Listener After a sample Custom logging or filtering
JSR223 Timer Before a sampler Calculate a delay

There are also older BeanShell equivalents, but they are slower and deprecated in practice. Prefer JSR223 with Groovy.

The objects you get

Inside a script these variables are available without declaring them:

Name What it is
vars The current thread's variables: vars.get("x"), vars.put("x", "1")
props JMeter properties (global): props.get("host"), props.put("token", t)
prev The previous sample result (in processors and assertions): prev.getResponseCode(), prev.getResponseDataAsString(), prev.getTime()
sampler The current sampler object
ctx The JMeter context (thread number, previous result, ...)
log A logger: log.info("message"), written to jmeter.log
SampleResult In a JSR223 Sampler, the result you fill in: SampleResult.setResponseData("ok", "UTF-8")
Parameters and args The script's Parameters field as a string and as an array
AssertionResult In a JSR223 Assertion: AssertionResult.setFailure(true)
OUT The console output stream

Variables hold strings: vars.get returns text, and vars.put expects text, although recent versions have putObject / getObject for any object (these are not saved in results).

Example: a pre-processor building a body

GROOVY
// JSR223 PreProcessor (Language: groovy)
import groovy.json.JsonOutput

def quantity = (vars.get("qty") ?: "1") as int
def body = [
    sku     : vars.get("sku"),
    quantity: quantity,
    total   : quantity * (vars.get("price") as BigDecimal)
]
vars.put("orderBody", JsonOutput.toJson(body))

The request's Body Data is then just ${orderBody}.

Example: a post-processor parsing JSON

GROOVY
// JSR223 PostProcessor
import groovy.json.JsonSlurper

def json = new JsonSlurper().parseText(prev.getResponseDataAsString())
def ids  = json.items.findAll { it.price > 10 }.collect { it.id }

vars.put("expensiveCount", ids.size().toString())
ids.eachWithIndex { id, i -> vars.put("expensiveId_${i + 1}", id.toString()) }

If the response is not valid JSON, parseText throws and the log shows the exception, so wrap risky code in try { ... } catch (Exception e) { log.warn("parse failed", e) } and set a default variable.

Example: a custom assertion

GROOVY
// JSR223 Assertion
def total = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString()).total
if (total <= 0) {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage("Total must be positive but was " + total)
}

Performance: cache the compiled script

Scripts are compiled when first run. For Groovy, always tick Cache compiled script if available in the element's panel and write the code in the Script box (not in an external file read on every call), and do not use ${variables} inside the script text, because changing text defeats caching and forces a recompile for each iteration. Pass dynamic values through the Parameters field or read them with vars.get("name") instead.

Other advice:

  • Keep scripts short; heavy computation inside load threads steals CPU from sending requests.
  • Do not do blocking I/O (like reading a big file) in each iteration; read once in a setUp Thread Group.
  • Do not use println in a loop; use log or OUT, and sparingly.
  • Make helper functions reusable with an external .groovy file loaded once, if scripts grow.
  • Remember properties (props) are shared among threads, so concurrent updates need care; vars are thread-local and safe.

Stand-in: mimic vars, props and prev

JS Stand-in: a pre- and post-processor with vars and prev

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Security note

A JSR223 script is arbitrary code running as you. Never run .jmx files from untrusted sources without reading their scripts, and never paste secrets into script text; read them from properties instead. In shared teams, review scripts as you would application code.

A second look: a counter without code

Before writing a script, check whether a built-in element does the job: a Counter for sequence numbers, Random Variable for random numbers, User Parameters for per-thread constants, __groovy(), __digest() or __time() functions for one-liners. Scripts are powerful but cost readability; use them when the built-in options end.

JS Stand-in: a signature helper (the kind of code a script holds)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

(This is a toy checksum for demonstration; use proper HMAC functions, such as __digest or Java's javax.crypto.Mac, for real signatures.)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which language is recommended for JMeter scripting elements?

    JSR223 with Groovy is faster (with compilation caching) and better supported than BeanShell.
  2. 2. Which object holds the current thread's variables?

    vars is thread-local; props is global to the JMeter instance.
  3. 3. Why should you avoid ${variables} inside the script text?

    Dynamic text forces recompilation. Use vars.get() or the Parameters field instead.
  4. 4. Which method reads the previous response body as text in a post-processor?

    prev is the previous SampleResult; getResponseDataAsString returns the body as a string.

Summary

  • JSR223 elements run Groovy scripts as sampler, pre/post-processor, assertion, listener or timer.
  • Use vars (thread), props (global), prev (last result), log (logging) and sampler.
  • Tick "Cache compiled script", keep code in the Script box and avoid ${...} inside scripts.
  • Try built-in elements and functions first; review scripts like code and keep secrets out of them.
  • Scripts run in load threads, so keep them light.

Next: Assertions in JMeter