QA and Test Automation · Lab 27 of 35
JMeter Load Test With Correlation: ShopRung Hands-On Lab
Build a JMeter test plan for ShopRung shoppers: sign up once per thread, carry the token, a random product id and the new order id from response to request with JSON extractors, assert status, body and duration, run it without the GUI, and add the pass/fail gate JMeter does not have.
⏱ 75 minIntermediate💸 Free7 steps
Apache JMeter 5.6Java 17+ (21 used)Python 3 (the gate)ShopRung
Overview video
What you will build
A JMeter test plan, shoprung.jmx, where every request depends on the one before, which is what correlation means:
- A thread group of shoppers whose count, ramp-up and duration come from the command line.
- Sign up once per thread, then the token from the response goes into every later request.
- A search whose response gives a random sticker id, which goes into add to cart; the order response gives the order id, which opens the order and checks it is PLACED.
- Assertions on status codes, the JSON body and a 500 ms duration, think time between steps, a non-GUI run with an HTML dashboard, and
gate.py, which fails the build when errors or p95 miss the goals, because JMeter itself exits 0 anyway.
Before you start
- The episode behind it: JMeter and Locust, and Performance metrics for p95.
- ShopRung installed, as in lab 1 setup.
- Java 17 or newer (JMeter runs on Java), and Python 3 for the gate.
Setup
S1Install JMeter
On a Mac, Homebrew installs JMeter and its Java. Elsewhere, download the binary zip from jmeter.apache.org, unzip it, and use bin/jmeter (Windows: bin\jmeter.bat).
brew install jmeter
jmeter --version# download apache-jmeter-5.6.3.zip from jmeter.apache.org, unzip, then:
./apache-jmeter-5.6.3/bin/jmeter --version# download apache-jmeter-5.6.3.zip from jmeter.apache.org, unzip, then:
.\apache-jmeter-5.6.3\bin\jmeter.bat --version ... 5.6.3 ...
S2Start ShopRung
Start ShopRung as in lab 1 with npm start, and make a folder shoprung-jmeter for the plan. Load test only your own copy of ShopRung.
curl http://localhost:8080/api/health
mkdir shoprung-jmeter && cd shoprung-jmetercurl http://localhost:8080/api/health
mkdir shoprung-jmeter && cd shoprung-jmetercurl.exe http://localhost:8080/api/health
mkdir shoprung-jmeter; cd shoprung-jmeter {"status":"UP","app":"ShopRung","version":"1.0.0"} The skeleton: defaults, threads, headers
A test plan that knows where ShopRung is and how many shoppers to simulate.
Open the GUI with jmeter (build plans in the GUI; never run load from it). Rename the Test Plan to ShopRung shoppers and add, by right-clicking:
- Add → Config Element → HTTP Request Defaults: Protocol
http, Server${__P(host,localhost)}, Port${__P(port,8080)}.__Preads a property from the command line, with a default, so the same plan can target another server. - Add → Threads → Thread Group, named Shoppers: Number of threads
${__P(users,5)}, Ramp-up${__P(rampup,10)}, Loop Count Infinite, tick Specify thread lifetime and set Duration${__P(duration,30)}. "Action after a Sampler error": Continue. - Inside the thread group, Add → Config Element → HTTP Header Manager with
Content-Type: application/jsonandAuthorization: Bearer ${token}. - Add → Timer → Uniform Random Timer: Constant delay 1000 ms, Random delay maximum 2000 ms: think time of 1 to 3 seconds before every request.
Save as shoprung.jmx in your folder. The full file is shown in step 5, and you can download it at the bottom of the page.
Sign up once, keep the token
Each thread creates its own account and stores the token from the response.
Inside the thread group: Add → Logic Controller → Once Only Controller, named Once per user. Inside it, Add → Sampler → HTTP Request named Sign up: method POST, path /api/auth/signup, and in Body Data:
{"name": "JMeter user ${__threadNum}", "email": "jm-${__threadNum}-${__UUID()}@shoprung.test", "password": "Load1234!"}
__threadNum is the thread's number and __UUID() a random id, so every thread in every run gets a new email. ShopRung answers 201 with a token, so no separate login is needed.
Under Sign up, add Assertions → Response Assertion (Field to test: Response Code, Pattern: 201) and Post Processors → JSON Extractor: Names of created variables token, JSON Path expressions $.token. This is the first correlation: a value from a response, stored as ${token}, sent by the Header Manager on every later request.
Carry ids from response to request
Search, add the found product, place the order, open that order.
After the Once Only Controller, add four HTTP Requests in order, each with a Response Assertion on its status code:
- Search stickers: GET
/api/products?q=sticker(assert200). Add a JSON Extractor: variableproductId, path$.items[*].id, Match No.0. The path matches both sticker packs; Match No. 0 picks one at random, so shoppers spread over both products. - Add to cart: POST
/api/cart/itemswith body{"productId": ${productId}, "quantity": 1}(assert200). - Place order: POST
/api/orders(assert201), with a JSON Extractor: variableorderId, path$.id. - Open order: GET
/api/orders/${orderId}(assert200), plus Assertions → JSON Assertion: path$.status, Expected ValuePLACED.
Name the last sampler Open order, not Open order ${orderId}. Names with variables become a separate row per value: our first run had ten rows, "Open order 234" to "Open order 243", in the report.
A response time goal and a quick check
Fail slow searches, and see one shopper work in the GUI.
Under Search stickers, add Assertions → Duration Assertion with 500 ms: a search that takes longer counts as failed, even with status 200.
Check the plan with a single shopper: add Listener → View Results Tree, press the green Start button with the thread count set to 1 for a moment, and click each sample: the request body of Add to cart shows a real id instead of ${productId}, and Open order shows the new order. Remove or disable the View Results Tree afterwards: it keeps every response in memory and slows real load runs.
The saved plan
What the GUI wrote: the plan as an XML file you keep in Git.
JMeter saves everything as XML. You will rarely edit it by hand, but you should recognise it in a code review: each element has its settings, and the hashTree that follows holds its children. Compare yours with this one.
<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
<hashTree>
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="ShopRung shoppers">
<boolProp name="TestPlan.functional_mode">false</boolProp>
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments">
<collectionProp name="Arguments.arguments"/>
</elementProp>
</TestPlan>
<hashTree>
<ConfigTestElement guiclass="HttpDefaultsGui" testclass="ConfigTestElement" testname="HTTP Request Defaults">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="HTTPSampler.domain">${__P(host,localhost)}</stringProp>
<stringProp name="HTTPSampler.port">${__P(port,8080)}</stringProp>
<stringProp name="HTTPSampler.protocol">http</stringProp>
</ConfigTestElement>
<hashTree/>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shoppers">
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController">
<intProp name="LoopController.loops">-1</intProp>
<boolProp name="LoopController.continue_forever">false</boolProp>
</elementProp>
<stringProp name="ThreadGroup.num_threads">${__P(users,5)}</stringProp>
<stringProp name="ThreadGroup.ramp_time">${__P(rampup,10)}</stringProp>
<boolProp name="ThreadGroup.scheduler">true</boolProp>
<stringProp name="ThreadGroup.duration">${__P(duration,30)}</stringProp>
<stringProp name="ThreadGroup.delay"/>
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
</ThreadGroup>
<hashTree>
<HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="JSON and the token">
<collectionProp name="HeaderManager.headers">
<elementProp name="" elementType="Header">
<stringProp name="Header.name">Content-Type</stringProp>
<stringProp name="Header.value">application/json</stringProp>
</elementProp>
<elementProp name="" elementType="Header">
<stringProp name="Header.name">Authorization</stringProp>
<stringProp name="Header.value">Bearer ${token}</stringProp>
</elementProp>
</collectionProp>
</HeaderManager>
<hashTree/>
<UniformRandomTimer guiclass="UniformRandomTimerGui" testclass="UniformRandomTimer" testname="Think time 1-3 s">
<stringProp name="ConstantTimer.delay">1000</stringProp>
<stringProp name="RandomTimer.range">2000</stringProp>
</UniformRandomTimer>
<hashTree/>
<OnceOnlyController guiclass="OnceOnlyControllerGui" testclass="OnceOnlyController" testname="Once per user"/>
<hashTree>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Sign up">
<boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
<collectionProp name="Arguments.arguments">
<elementProp name="" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">{"name": "JMeter user ${__threadNum}", "email": "jm-${__threadNum}-${__UUID()}@shoprung.test", "password": "Load1234!"}</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
</elementProp>
</collectionProp>
</elementProp>
<stringProp name="HTTPSampler.path">/api/auth/signup</stringProp>
<stringProp name="HTTPSampler.method">POST</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
</HTTPSamplerProxy>
<hashTree>
<ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="201 Created">
<collectionProp name="Asserion.test_strings">
<stringProp name="0">201</stringProp>
</collectionProp>
<stringProp name="Assertion.custom_message"/>
<stringProp name="Assertion.test_field">Assertion.response_code</stringProp>
<boolProp name="Assertion.assume_success">false</boolProp>
<intProp name="Assertion.test_type">8</intProp>
</ResponseAssertion>
<hashTree/>
<JSONPostProcessor guiclass="JSONPostProcessorGui" testclass="JSONPostProcessor" testname="token from the response">
<stringProp name="JSONPostProcessor.referenceNames">token</stringProp>
<stringProp name="JSONPostProcessor.jsonPathExprs">$.token</stringProp>
<stringProp name="JSONPostProcessor.match_numbers">1</stringProp>
<stringProp name="JSONPostProcessor.defaultValues">NOT_FOUND</stringProp>
</JSONPostProcessor>
<hashTree/>
</hashTree>
</hashTree>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Search stickers">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="HTTPSampler.path">/api/products?q=sticker</stringProp>
<stringProp name="HTTPSampler.method">GET</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
</HTTPSamplerProxy>
<hashTree>
<ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="200 OK">
<collectionProp name="Asserion.test_strings">
<stringProp name="0">200</stringProp>
</collectionProp>
<stringProp name="Assertion.custom_message"/>
<stringProp name="Assertion.test_field">Assertion.response_code</stringProp>
<boolProp name="Assertion.assume_success">false</boolProp>
<intProp name="Assertion.test_type">8</intProp>
</ResponseAssertion>
<hashTree/>
<DurationAssertion guiclass="DurationAssertionGui" testclass="DurationAssertion" testname="Under 500 ms">
<stringProp name="DurationAssertion.duration">500</stringProp>
</DurationAssertion>
<hashTree/>
<JSONPostProcessor guiclass="JSONPostProcessorGui" testclass="JSONPostProcessor" testname="a random sticker id">
<stringProp name="JSONPostProcessor.referenceNames">productId</stringProp>
<stringProp name="JSONPostProcessor.jsonPathExprs">$.items[*].id</stringProp>
<stringProp name="JSONPostProcessor.match_numbers">0</stringProp>
<stringProp name="JSONPostProcessor.defaultValues">NOT_FOUND</stringProp>
</JSONPostProcessor>
<hashTree/>
</hashTree>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Add to cart">
<boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
<collectionProp name="Arguments.arguments">
<elementProp name="" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">{"productId": ${productId}, "quantity": 1}</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
</elementProp>
</collectionProp>
</elementProp>
<stringProp name="HTTPSampler.path">/api/cart/items</stringProp>
<stringProp name="HTTPSampler.method">POST</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
</HTTPSamplerProxy>
<hashTree>
<ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="200 OK">
<collectionProp name="Asserion.test_strings">
<stringProp name="0">200</stringProp>
</collectionProp>
<stringProp name="Assertion.custom_message"/>
<stringProp name="Assertion.test_field">Assertion.response_code</stringProp>
<boolProp name="Assertion.assume_success">false</boolProp>
<intProp name="Assertion.test_type">8</intProp>
</ResponseAssertion>
<hashTree/>
</hashTree>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Place order">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="HTTPSampler.path">/api/orders</stringProp>
<stringProp name="HTTPSampler.method">POST</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
</HTTPSamplerProxy>
<hashTree>
<ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="201 Created">
<collectionProp name="Asserion.test_strings">
<stringProp name="0">201</stringProp>
</collectionProp>
<stringProp name="Assertion.custom_message"/>
<stringProp name="Assertion.test_field">Assertion.response_code</stringProp>
<boolProp name="Assertion.assume_success">false</boolProp>
<intProp name="Assertion.test_type">8</intProp>
</ResponseAssertion>
<hashTree/>
<JSONPostProcessor guiclass="JSONPostProcessorGui" testclass="JSONPostProcessor" testname="the new order id">
<stringProp name="JSONPostProcessor.referenceNames">orderId</stringProp>
<stringProp name="JSONPostProcessor.jsonPathExprs">$.id</stringProp>
<stringProp name="JSONPostProcessor.match_numbers">1</stringProp>
<stringProp name="JSONPostProcessor.defaultValues">NOT_FOUND</stringProp>
</JSONPostProcessor>
<hashTree/>
</hashTree>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Open order">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="HTTPSampler.path">/api/orders/${orderId}</stringProp>
<stringProp name="HTTPSampler.method">GET</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
</HTTPSamplerProxy>
<hashTree>
<ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="200 OK">
<collectionProp name="Asserion.test_strings">
<stringProp name="0">200</stringProp>
</collectionProp>
<stringProp name="Assertion.custom_message"/>
<stringProp name="Assertion.test_field">Assertion.response_code</stringProp>
<boolProp name="Assertion.assume_success">false</boolProp>
<intProp name="Assertion.test_type">8</intProp>
</ResponseAssertion>
<hashTree/>
<JSONPathAssertion guiclass="JSONPathAssertionGui" testclass="JSONPathAssertion" testname="status is PLACED">
<stringProp name="JSON_PATH">$.status</stringProp>
<stringProp name="EXPECTED_VALUE">PLACED</stringProp>
<boolProp name="JSONVALIDATION">true</boolProp>
<boolProp name="EXPECT_NULL">false</boolProp>
<boolProp name="INVERT">false</boolProp>
<boolProp name="ISREGEX">false</boolProp>
</JSONPathAssertion>
<hashTree/>
</hashTree>
</hashTree>
</hashTree>
</hashTree>
</jmeterTestPlan> - Host and port come from -Jhost and -Jport on the command line.line 17
- Shoppers, ramp-up and duration are properties too: no plan edits between runs.line 27
- Sent with every request; empty until Sign up has run.line 43
- Think time: 1000 ms plus up to 2000 ms random.line 50
- A unique email per thread and run.line 61
- Correlation 1: the token from the sign-up response.line 84
- A search slower than 500 ms is a failed sample.line 112
- Correlation 2: the ids of the products found...line 117
- ...and Match No. 0 picks one at random.line 118
- The extracted id goes into the next request's body.line 129
- Correlation 3: the new order's id.line 173
- Check the body, not only the status.line 201
Run it without the GUI
A real load run and an HTML dashboard.
Close the GUI and run from the terminal: -n no GUI, -t the plan, -J the properties, -l the raw results file, -e -o report generate the HTML dashboard into report/ (the folder must not exist yet).
The summary lines every 30 seconds show throughput, times and errors. Open report/index.html: the Statistics table has one row per sampler, with percentiles and error percentages. We placed 14 orders in 30 seconds, and the sticker stock in ShopRung fell by exactly 14: the random product ids really reached the cart.
rm -rf report results.jtl
jmeter -n -t shoprung.jmx -Jport=8080 -Jusers=5 -Jduration=30 -l results.jtl -e -o report
echo "exit code: $?"rm -rf report results.jtl
jmeter -n -t shoprung.jmx -Jport=8080 -Jusers=5 -Jduration=30 -l results.jtl -e -o report
echo "exit code: $?"Remove-Item -Recurse -Force report, results.jtl -ErrorAction SilentlyContinue
jmeter.bat -n -t shoprung.jmx -Jport=8080 -Jusers=5 -Jduration=30 -l results.jtl -e -o report
echo "exit code: $LASTEXITCODE" Creating summariser <summary> Created the tree successfully using shoprung.jmx Starting standalone test @ ... summary + 1 in 00:00:01 = 0.8/s Avg: 20 Min: 20 Max: 20 Err: 0 (0.00%) Active: 1 Started: 1 Finished: 0 summary + 61 in 00:00:28 = 2.2/s Avg: 4 Min: 1 Max: 27 Err: 0 (0.00%) Active: 0 Started: 5 Finished: 5 summary = 62 in 00:00:30 = 2.1/s Avg: 4 Min: 1 Max: 27 Err: 0 (0.00%) Tidying up ... ... end of run exit code: 0
Stuck on this step?
- "Results file ... is not empty" or "report folder ... is not empty".
- Delete
results.jtlandreport/before each run (the first line of the command does). - Every request after Sign up fails with 401.
- The token was not extracted: check the JSON Extractor is under Sign up, with
$.token, and that the header saysBearer ${token}.
A gate, because JMeter says yes anyway
Fail the build when errors or p95 miss the goals.
Switch on ShopRung's slow-search bug and run again. Every search takes 2.5 seconds, the Duration Assertion fails all 14 of them, the error rate is 29.17%, and JMeter still exits 0. A CI job would stay green.
Create gate.py. It reads report/statistics.json, which the dashboard step wrote, prints a table, and exits 1 when total errors exceed 1% or the 95th percentile exceeds 500 ms. Run it after JMeter in CI. Turn the bug off at the end.
"""Fail the build when a JMeter run misses its goals. JMeter itself exits 0 even when samples fail.
Usage: python3 gate.py report/statistics.json"""
import json
import sys
MAX_ERROR_PCT = 1.0 # at most 1% failed samples
MAX_P95_MS = 500 # 95% of samples within 500 ms
stats = json.load(open(sys.argv[1]))
total = stats["Total"]
p95 = total["pct2ResTime"] # JMeter's dashboard: pct1 = 90th, pct2 = 95th, pct3 = 99th percentile
print(f"{'request':20} {'samples':>8} {'errors':>8} {'p95 ms':>8}")
for name, row in stats.items():
print(f"{name:20} {row['sampleCount']:>8} {row['errorPct']:>7.1f}% {row['pct2ResTime']:>8.0f}")
problems = []
if total["errorPct"] > MAX_ERROR_PCT:
problems.append(f"errors {total['errorPct']:.1f}% > {MAX_ERROR_PCT}%")
if p95 > MAX_P95_MS:
problems.append(f"p95 {p95:.0f} ms > {MAX_P95_MS} ms")
if problems:
print("GATE FAILED: " + "; ".join(problems))
sys.exit(1)
print("GATE PASSED") - The goals, written down where everyone can see them.line 6
- The dashboard's 95th percentile (pct1 is the 90th, pct3 the 99th).line 11
- This is the exit code CI acts on.line 24
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["slow-search"]}'
rm -rf report results.jtl
jmeter -n -t shoprung.jmx -Jusers=5 -Jduration=30 -l results.jtl -e -o report; echo "jmeter exit code: $?"
python3 gate.py report/statistics.json; echo "gate exit code: $?" summary = 48 in 00:00:32 = 1.5/s Avg: 734 Min: 1 Max: 2505 Err: 14 (29.17%) jmeter exit code: 0 request samples errors p95 ms Place order 9 0.0% 8 Open order 9 0.0% 4 Add to cart 11 0.0% 6 Total 48 29.2% 2505 Search stickers 14 100.0% 2505 Sign up 5 0.0% 23 GATE FAILED: errors 29.2% > 1.0%; p95 2505 ms > 500 ms gate exit code: 1
Check it works
With all bugs off, run the plan and the gate: 0 errors, and gate.py prints GATE PASSED with exit code 0. In ShopRung, the two sticker packs' stock together has fallen by exactly the number of Place order samples.
With slow-search on: Search stickers fails 100% with "The operation lasted too long", JMeter still exits 0, and gate.py prints GATE FAILED and exits 1. Turn the bug off.
python3 gate.py report/statistics.json request samples errors p95 ms Place order 14 0.0% 7 Open order 12 0.0% 3 Add to cart 15 0.0% 6 Total 62 0.0% 21 Search stickers 16 0.0% 4 Sign up 5 0.0% 27 GATE PASSED
Troubleshooting
Add to cart sends {"productId": NOT_FOUND, ...} and fails.
The JSON Extractor did not match: check $.items[*].id and that it sits under Search stickers, not elsewhere.
Sign up fails with 409 on a second run.
The email repeats. Keep ${__UUID()} in it so every run creates new accounts.
Place order fails with 409 after long runs.
Stock ran out. Restart ShopRung or POST /api/test/reset between runs, or lower users and duration.
The report has one row per order.
Remove variables from sampler names: "Open order", not "Open order ${orderId}".
JMeter runs slowly or runs out of memory.
Run with -n, disable View Results Tree and other GUI listeners, and write results to a file with -l instead.
What changes in production
- Plans are built in the GUI, saved in Git, reviewed as XML, and run with
-nin CI or on dedicated load machines, often several in distributed mode. - Correlation is the main work in recorded scripts: tokens, CSRF values, ids and session cookies extracted and reused.
- Goals are enforced outside JMeter: a gate on the dashboard's statistics.json, or a plugin, decides pass or fail.
- Teams parameterise users, duration and hosts with properties, and feed test data from CSV Data Set Config files.
Interview angle
“What is correlation, and how did you do it in JMeter?”
Correlation is taking a dynamic value from one response and sending it in a later request, because tokens and ids change every run. In our ShopRung plan, each thread signed up once inside a Once Only Controller; a JSON Extractor stored the token, which the Header Manager sent as Bearer on every request. A search extracted a random product id with Match No. 0, which went into the add-to-cart body, and the order response gave the order id that we opened and asserted as PLACED. Stock fell by exactly the number of orders, which proved the ids flowed. We ran non-GUI with an HTML dashboard and added a gate, because JMeter exits 0 even with 29% failed samples.
Clean up
Practice
These run in your browser and check your answer.
A JSON path, by hand
JMeter's JSON Extractor reads values with paths like $.items[*].id. Write ids(response) that returns every product id in a ShopRung search response (a dict with an items list), and pick(ids, match) that returns the id for a Match No.: 1 for the first, 2 for the second, and -1 for all of them as a list (0 means random, which you can skip).
def ids(response):
return [item["id"] for item in response["items"]]
def pick(ids, match):
return ids[match]
Hint
Match No. 1 is index 0. Handle -1 first and return the whole list.
The full project
Every file from this lab, as it is after the last step.