JMeter Scripting with Groovy: Custom Samplers, Pre- and Post-Processors

JMeter Scripting with Groovy: Custom Samplers, Pre- and Post-Processors

JMeter's built-in samplers cover most testing scenarios, but they hit a wall when your application has custom authentication schemes, complex data transformations, or non-HTTP protocols. Groovy scripting fills that gap. With JSR223 samplers and processors, you get a full programming language inside your test plan.

This guide covers practical Groovy scripting patterns for JMeter: from basic variable manipulation to custom samplers that replace multiple HTTP requests.

Why Groovy (Not BeanShell)

JMeter supports several scripting languages via JSR223: BeanShell, JavaScript (Nashorn), and Groovy. Always use Groovy.

BeanShell is slow — it interprets code on every execution without JIT compilation. For a test with 1,000 threads each running 100 iterations, BeanShell in a pre-processor becomes a significant bottleneck. Groovy compiles to bytecode and caches compiled scripts, making it roughly 10-20x faster for repeated execution.

Enable script caching in JSR223 elements by checking the "Cache compiled script if available" checkbox (it's checked by default in modern JMeter versions).

JSR223 Sampler: Your Swiss Army Knife

The JSR223 Sampler executes a script as a test step and lets you control the sample result directly.

Basic Structure

import org.apache.jmeter.samplers.SampleResult

// Access JMeter variables and properties
def userId = vars.get("user_id")
def apiKey = props.get("api.key")
def threadNum = ctx.getThreadNum()

// Make an HTTP request using Groovy's built-in HTTP client
def url = new URL("https://api.example.com/users/${userId}")
def connection = url.openConnection()
connection.setRequestProperty("Authorization", "Bearer ${apiKey}")
connection.setRequestProperty("Content-Type", "application/json")

def responseCode = connection.responseCode
def responseBody = connection.inputStream.text

// Set sample result
SampleResult.setResponseCode(responseCode.toString())
SampleResult.setResponseData(responseBody, "UTF-8")
SampleResult.setSuccessful(responseCode == 200)
SampleResult.setSampleLabel("Custom API Call - User ${userId}")

Key Objects Available in Scripts

Object Type Description
vars JMeterVariables Thread-local variables (read/write)
props JMeterProperties Global properties (read/write)
ctx JMeterContext Current thread context
sampler Current sampler The sampler element itself
prev SampleResult Result of the previous sampler
log Logger Write to jmeter.log
OUT PrintStream Write to console
SampleResult SampleResult The current sample result (JSR223 Sampler only)

Pre-Processors: Prepare Data Before Each Request

JSR223 Pre-Processors run before the sampler in the same scope. Use them for:

Dynamic Request Signing

HMAC-signed API requests are a common real-world requirement that JMeter can't handle natively:

import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import java.util.Base64

def secretKey = vars.get("secret_key")
def requestBody = vars.get("request_body")
def timestamp = System.currentTimeMillis().toString()

// Create HMAC-SHA256 signature
def mac = Mac.getInstance("HmacSHA256")
def keySpec = new SecretKeySpec(secretKey.bytes, "HmacSHA256")
mac.init(keySpec)
def payload = "${timestamp}${requestBody}"
def signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.bytes))

// Store for use in HTTP request headers
vars.put("request_timestamp", timestamp)
vars.put("request_signature", signature)

log.info("Generated signature for request at ${timestamp}")

In the HTTP Request sampler, add headers:

  • X-Timestamp: ${request_timestamp}
  • X-Signature: ${request_signature}

Generating Complex JSON Bodies

Instead of using the HTTP Request body directly with string interpolation (fragile with special characters), build the JSON in Groovy:

import groovy.json.JsonOutput

def requestData = [
    userId: vars.get("user_id"),
    action: "purchase",
    items: [
        [productId: vars.get("product_id"), quantity: vars.get("qty").toInteger()],
    ],
    metadata: [
        sessionId: vars.get("JMeterThread.last_sample_ok"),
        timestamp: new Date().format("yyyy-MM-dd'T'HH:mm:ss'Z'")
    ]
]

vars.put("request_body", JsonOutput.toJson(requestData))

Set the HTTP Request body to ${request_body}.

Thread-Local Setup

Run setup logic once per thread (not once per iteration) by checking the thread number:

def threadId = ctx.getThreadNum().toString()
def setupDoneKey = "setup_done_${threadId}"

if (vars.get(setupDoneKey) == null) {
    // First iteration for this thread — do setup
    def loginResult = performLogin(vars.get("username"), vars.get("password"))
    vars.put("auth_token", loginResult.token)
    vars.put("session_id", loginResult.sessionId)
    vars.put(setupDoneKey, "true")
    log.info("Thread ${threadId}: setup complete, auth token acquired")
}

Post-Processors: Extract and Transform Response Data

JSR223 Post-Processors run after the sampler. They're most useful when regex or JSON extractors aren't flexible enough.

Complex JSON Parsing

import groovy.json.JsonSlurper

def responseBody = prev.getResponseDataAsString()
def json = new JsonSlurper().parseText(responseBody)

// Extract nested values
def orderId = json.data?.order?.id
def totalAmount = json.data?.order?.total?.amount
def itemCount = json.data?.order?.items?.size()

if (orderId) {
    vars.put("order_id", orderId.toString())
    vars.put("order_total", totalAmount?.toString() ?: "0")
    vars.put("order_item_count", itemCount?.toString() ?: "0")
    log.info("Extracted order ${orderId} with ${itemCount} items")
} else {
    log.warn("Could not extract order ID from response: ${responseBody.take(200)}")
    vars.put("order_id", "")
}

Conditional Assertions

Standard JMeter assertions fail the entire sample. Post-processors let you implement conditional logic:

def responseBody = prev.getResponseDataAsString()
def responseCode = prev.getResponseCode()

// Accept both 200 and 201 as success
if (responseCode == "200" || responseCode == "201") {
    prev.setSuccessful(true)
} else if (responseCode == "429") {
    // Rate limited — mark as warning but don't fail
    prev.setSuccessful(true)
    vars.put("rate_limited", "true")
    log.warn("Rate limited on thread ${ctx.getThreadNum()}")
} else {
    prev.setSuccessful(false)
    prev.setResponseMessage("Unexpected status: ${responseCode}")
}

Storing Data for Later in the Test

Use props (global properties) instead of vars (thread-local) when you need to share data across threads:

// Post-processor on "Create Resource" request
def resourceId = // ... parse from response

// Share across all threads (useful for read-heavy tests that share a resource)
props.put("shared_resource_id", resourceId.toString())
log.info("Published resource ${resourceId} to all threads")

Then in other threads: def resourceId = props.get("shared_resource_id")

Custom Samplers for Non-HTTP Protocols

JMeter has native samplers for JDBC, JMS, and TCP, but for custom protocols (internal RPC, proprietary binary protocols, gRPC without a plugin), a JSR223 Sampler is the way in.

gRPC Example (Without Plugin)

import io.grpc.ManagedChannelBuilder
import io.grpc.StatusRuntimeException
import com.example.proto.UserServiceGrpc
import com.example.proto.UserRequest

def host = vars.get("grpc_host")
def port = vars.get("grpc_port").toInteger()

def channel = ManagedChannelBuilder.forAddress(host, port)
    .usePlaintext()
    .build()

def stub = UserServiceGrpc.newBlockingStub(channel)

try {
    def request = UserRequest.newBuilder()
        .setUserId(vars.get("user_id"))
        .build()
    
    def startTime = System.currentTimeMillis()
    def response = stub.getUser(request)
    def elapsed = System.currentTimeMillis() - startTime
    
    SampleResult.setResponseData(response.toString(), "UTF-8")
    SampleResult.setResponseCode("0")
    SampleResult.setSuccessful(true)
    SampleResult.setEndTime(SampleResult.getStartTime() + elapsed)
    
    vars.put("user_name", response.getName())
} catch (StatusRuntimeException e) {
    SampleResult.setSuccessful(false)
    SampleResult.setResponseCode(e.getStatus().getCode().toString())
    SampleResult.setResponseMessage(e.getMessage())
} finally {
    channel.shutdownNow()
}

Add the gRPC JAR files to JMETER_HOME/lib/ext/.

Working with External Libraries

To use third-party libraries in your scripts:

  1. Add JAR files to JMETER_HOME/lib/ext/
  2. Restart JMeter
  3. Import normally in your script: import com.example.MyClass

For Maven dependencies, the JMeter Maven Plugin has a <jmeterExtensions> section that downloads dependencies automatically as part of CI.

Debugging Groovy Scripts

Print to console:

OUT.println("Debug: userId = ${vars.get('user_id')}")

Write to JMeter log:

log.debug("Processing thread ${ctx.getThreadNum()}")
log.info("Extracted ${items.size()} items from response")
log.error("Failed to parse JSON: ${e.message}")

View log output in View > Log Viewer in the GUI, or in jmeter.log file.

Test scripts interactively using the Script Console (Options > Script Console in newer JMeter). You can run Groovy code and inspect results before embedding it in a test plan.

Performance Considerations

A few rules to keep Groovy scripts from becoming bottlenecks:

  1. Check the cache checkbox on all JSR223 elements — compiled scripts are dramatically faster
  2. Avoid object creation in tight loops — instantiate expensive objects once (outside the sampler), store in vars
  3. Don't open connections in pre-processors if you can reuse them across iterations
  4. Log at DEBUG level for diagnostic info — logging at INFO level in 1,000 threads floods the log file
// Expensive — creates new JsonSlurper every iteration
def json = new JsonSlurper().parseText(vars.get("data"))

// Better — reuse if JsonSlurper is stateless (it is)
// Just be aware of the tradeoff between clarity and performance

Wrapping Up

Groovy scripting in JMeter unlocks the scenarios where point-and-click configuration runs out of room: custom auth, complex data generation, non-HTTP protocols, and dynamic assertions. The learning curve is real, but the JSR223 sampler/processor pair covers a surprisingly wide surface area.

Start with the objects available in scripts (vars, props, prev, ctx) and build from there. Most complex test plan requirements come down to combinations of pre-processors that prepare data and post-processors that extract it.

Read more

Start now free