Using BeanShell in Apache JMeter for Complex E‑commerce Test Scenarios
This article explains how to use BeanShell within Apache JMeter to create custom pre‑processor, post‑processor, and sampler scripts for complex e‑commerce testing, detailing step‑by‑step procedures and providing multiple practical code examples such as extracting JSON fields, generating order IDs, and managing authentication tokens.
BeanShell is a powerful pre‑processor, post‑processor, and sampler in Apache JMeter that allows testers to write custom Java‑like scripts for handling complex business logic, manipulating request data, and dynamically generating or modifying test data.
Basic steps:
Add a BeanShell Sampler, PreProcessor, or PostProcessor to the appropriate location in the Thread Group.
Write the script in the "Script" area, using Java/BeanShell syntax and accessing JMeter variables via ${variable} , the vars object, or the props object.
Call JMeter API methods directly within the script to set variables, retrieve system information, or manipulate HTTP requests.
Debug using log.info() to print messages to jmeter.log and verify script behavior.
Example 1 – Extract a JSON field from the previous HTTP response:
import org.json.JSONObject;
// Get previous response body
String prevResponse = new String(prev.getResponseData());
// Convert to JSON object
JSONObject jsonObject = new JSONObject(prevResponse);
// Extract "item_id"
String itemId = jsonObject.getString("item_id");
// Store for next request
vars.put("next_request_item_id", itemId);This script obtains the prior response, parses it as JSON, extracts the item_id field, and stores it in a new JMeter variable.
Example 2 – Dynamically generate a unique order ID:
import java.util.UUID;
// Generate unique order ID
String orderId = UUID.randomUUID().toString();
vars.put("order_id", orderId);
log.info("Generated unique order ID: " + orderId);Example 3 – Update cart quantity based on response JSON:
import org.json.*;
String response = new String(prev.getResponseData());
JSONObject jsonObject = new JSONObject(response);
JSONArray cartItems = jsonObject.getJSONArray("cart");
for (int i = 0; i < cartItems.length(); i++) {
JSONObject item = cartItems.getJSONObject(i);
if ("product2".equals(item.getString("id"))) {
int currentQuantity = item.getInt("quantity");
item.put("quantity", currentQuantity + 1);
vars.put("new_product_b_quantity", Integer.toString(currentQuantity + 1));
}
}
String updatedCartJson = jsonObject.toString();
vars.put("updated_cart", updatedCartJson);Example 4 – Manage and refresh an authentication token:
String token = vars.get("user_token");
long currentTime = System.currentTimeMillis() / 1000;
if (token != null && currentTime - Long.parseLong(vars.get("token_expiration_time")) > 3600) {
// Token expired, re‑login to obtain a new one (simplified)
Map tokenInfo = login(username, password);
token = (String) tokenInfo.get("token");
vars.put("user_token", token);
vars.put("token_expiration_time", Long.toString(currentTime + (Long) tokenInfo.get("expiration_seconds")));
}
// Add token to request header
sampler.getHeaderManager().add(new Header("Authorization", "Bearer " + token));Example 5 – Compare displayed price with stored price:
String response = prev.getResponseDataAsString();
int displayedPrice = -1;
Matcher matcher = Pattern.compile("(\\d+(?:\\.\\d+)?)").matcher(response);
if (matcher.find()) {
displayedPrice = Float.parseFloat(matcher.group(1));
}
String storedPriceStr = vars.get("stored_product_price");
double storedPrice = Double.parseDouble(storedPriceStr);
if (displayedPrice != storedPrice) {
log.error("Price mismatch! Displayed: " + displayedPrice + ", Stored: " + storedPrice);
Failure = true;
} else {
log.info("Price verification succeeded, displayed price matches stored price.");
}Example 6 – Synchronize inventory after order creation:
import org.json.*;
String response = prev.getResponseDataAsString();
JSONObject orderJson = new JSONObject(response);
JSONArray items = orderJson.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
String productId = item.getString("productId");
int quantity = item.getInt("quantity");
int currentStock = Integer.parseInt(vars.get("stock_" + productId));
currentStock -= quantity;
vars.put("stock_" + productId, Integer.toString(currentStock));
log.info("Product " + productId + " inventory updated to: " + currentStock);
}These cases demonstrate how BeanShell can be applied to various e‑commerce testing workflows, but because BeanShell has lower execution efficiency, it is recommended to use the JSR223 Sampler with Groovy for better performance in real‑world load testing.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.