Skip to main content

Load Testing Examples

These tests require your own reachable backend and TestFly 1.1.0 (setup). Adapt paths, payloads and thresholds to your application.

Health smoke​

import io.testfly.loadtest.BaseLoadTest;
import org.testng.annotations.Test;
import java.time.Duration;

public class HealthLoadTest extends BaseLoadTest {
@Test
public void healthUnderLoad() {
load("/health").engine("jdk").users(10)
.rampUp(Duration.ofSeconds(2)).hold(Duration.ofSeconds(5))
.run().assertP95Below(250).assertErrorRateBelow(0.01);
}
}

Login and payment​

Create testdata/users.csv on the filesystem or classpath:

username,password
demo-user,demo-password
import io.testfly.loadtest.BaseLoadTest;
import io.testfly.loadtest.LoadTestFeeder;
import org.testng.annotations.Test;
import java.time.Duration;
import java.util.Map;

public class CheckoutLoadTest extends BaseLoadTest {
@Test
public void checkout() {
loadScenario("Checkout")
.engine("jdk").users(15).hold(Duration.ofSeconds(10))
.feed(LoadTestFeeder.csv("testdata/users.csv"))
.step("Login").post("/login")
.body(Map.of("username", "${username}", "password", "${password}"))
.check(status().is(200)).extract("token", "$.accessToken").and()
.step("Payment").post("/payment")
.header("Authorization", "Bearer ${token}")
.body(Map.of("amount", 10)).check(status().is(200)).and()
.run().assertStepP95Below("Login", 300)
.assertStepP95Below("Payment", 800)
.assertStepErrorRateBelow("Payment", 0.01);
}
}

Combining UI and load coverage​

Keep UI tests in BaseTest classes and load tests in BaseLoadTest classes in the same TestNG suite. Use separate suites/processes if UI checks must observe a service during load. Do not assume CompletableFuture.runAsync() carries TestFly’s thread-local test ID or annotation context to a background load run. BaseTest does not provide load() and BaseLoadTest does not start a WebDriver.

Feature examples (1.1.0)​

The examples below show one load-test feature per section. They use APIs added in 1.1.0 (@TestFlyApi(since = "1.1.0")). They are methods of one TestNG class, ShopLoadTest; its class-level @LoadTest supplies the base URL and the default users/rampUp/hold shape. The class compiles against the current API, but the requests need your own backend, data files and credentials, so adapt the paths, files and thresholds.

package com.example.load;

import io.testfly.loadtest.*;
import org.testng.annotations.Test;

import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Map;

import static io.testfly.loadtest.ClosedStep.*;
import static io.testfly.loadtest.LoadStep.*;
import static io.testfly.loadtest.OpenStep.*;

@LoadTest(users = 50, rampUp = "10s", hold = "1m", baseUrl = "https://shop.example.com")
public class ShopLoadTest extends BaseLoadTest {
// the methods of the following sections go here
}

The class sets no engine, so auto applies: Gatling when it is on the test classpath, otherwise the JDK engine (see Engines). Sections marked Gatling only fail before any request when the JDK engine is resolved.

Multi-step checkout with correlation​

Each step reads values from the previous responses: a JSONPath token, a product id, a response header with a default value and a regex group. A queue() feeder hands out each CSV row once per run, and assertFeederNotExhausted() fails the test if the rows ran out. A String body that starts with { is sent as application/json. See Correlation, Request Content-Type, Feeder strategies and Journey assertions.

@Test
public void checkoutFlow() {
loadScenario("Checkout")
.users(100)
.feed(LoadTestFeeder.csv("data/users.csv").queue()) // each row once
.addFeeder(LoadTestFeeder.uuid("requestId"))
.step("Login")
.post("/api/auth/login")
.body(Map.of("user", "${username}", "password", "${password}"))
.check(status().is(200))
.extract("token", "$.accessToken") // JSONPath
.and()
.step("Search")
.get("/api/products")
.queryParam("q", "laptop")
.header("Authorization", "Bearer ${token}")
.header("X-Request-Id", "${requestId}")
.check(jsonPath("$.items[0].id").exists())
.extract("productId", jsonPath("$.items[0].id"))
.extract("etag", responseHeader("ETag"), "none") // header, with a default
.and()
.step("Add to cart")
.post("/api/cart")
.header("Authorization", "Bearer ${token}")
.body("{\"productId\":\"${productId}\",\"qty\":1}") // JSON Content-Type inferred
.check(status().in(200, 201))
.extract("cartId", regex("\"cartId\":\"([^\"]+)\"")) // regex group 1
.and()
.step("Coupon (form)")
.post("/api/coupon")
.formParam("code", "WELCOME10")
.check(status().is(204))
.and()
.thinkTime(500, 2000)
.run()
.assertP95Below(600)
.assertStepP95Below("Add to cart", 400)
.assertStepErrorRateBelow("Login", 0.001)
.assertFeederNotExhausted();
}

Open workload​

Gatling only. An open workload sets how fast users arrive, whatever the number already running; each user runs the steps once. A workload replaces users/rampUp/hold: the class-level values are ignored with an INFO line. See Workload models.

@Test
public void openWorkloadSpike() {
loadScenario("Browse - open model")
.workload(Workload.open(
nothingFor(Duration.ofSeconds(5)),
atOnce(20),
rampRate(5, 50, Duration.ofMinutes(2)), // 5 -> 50 users/s
constantRate(50, Duration.ofMinutes(5)),
stressPeak(500, Duration.ofSeconds(20)))) // sudden spike
.step("Home").get("/").and()
.step("Product").get("/api/products/42").and()
.run()
.assertErrorRateBelow(0.02);
}

Closed workload and soak​

Gatling only. A closed workload keeps a number of users running at the same time and replaces each user that finishes, which suits a long soak. Write the ramp-down as rampConcurrent(n, 0, duration). See Workload models.

@Test
public void closedWorkloadSoak() {
loadScenario("Soak - closed model")
.workload(Workload.closed(
rampConcurrent(0, 100, Duration.ofMinutes(2)),
constantConcurrent(100, Duration.ofMinutes(30)),
rampConcurrent(100, 0, Duration.ofMinutes(1)))) // ramp-down
.step("Orders").get("/api/orders").and()
.run()
.assertP95Below(500);
}

Flow control​

group, repeat, doIf/doIfOrElse, randomSwitch, tryMax and pace run on both engines with the same semantics. Here the top-level pace paces whole iterations of the users/rampUp/hold loop. With a workload, a top-level pace is rejected before any request: put it inside a repeat instead. See Flow control and Pacing.

@Test
public void userJourneyWithFlowControl() {
loadScenario("Journey")
.users(50)
.feed(LoadTestFeeder.json("data/customers.json").shuffle())
.pace(Duration.ofSeconds(3)) // at least 3 s per iteration
.group("Auth", g -> g
.step("Login").post("/api/login")
.body(Map.of("user", "${username}"))
.extract("role", jsonPath("$.role"), "guest"))
.repeat(5, "page", r -> r
.step("List page").get("/api/products?page=${page}"))
.doIfOrElse(LoadCondition.equalTo("role", "admin"),
admin -> admin.step("Admin dashboard").get("/api/admin/stats"),
user -> user.step("My orders").get("/api/me/orders"))
.randomSwitch(
LoadBranch.percent(70, b -> b.step("Browse").get("/api/categories")),
LoadBranch.percent(25, b -> b.step("Search").get("/api/search?q=tv")),
LoadBranch.percent(5, b -> b.step("Checkout").post("/api/checkout")))
.tryMax(3, t -> t
.step("Flaky payment").post("/api/pay")
.check(status().is(200)))
.doIf(LoadCondition.exists("couponCode"),
c -> c.step("Apply coupon").post("/api/coupon/${couponCode}"))
.run()
.assertErrorRateBelow(0.05);
}

Feeder strategies​

A scenario can combine several feeders: a ;-separated CSV with a random pick per iteration, in-memory records cycled in order, and the generated sequence, random and constant feeders. Strategies (circular, queue, shuffle, randomOrder) apply to csv, json and records feeders only. See Feeder strategies and In-memory records.

@Test
public void feeders() {
loadScenario("Feeders")
.users(20)
.feed(LoadTestFeeder.csv("data/products.csv", ';').randomOrder()) // ;-separated CSV
.addFeeder(LoadTestFeeder.records(List.of(
Map.of("region", "eu"), Map.of("region", "us"))).circular())
.addFeeder(LoadTestFeeder.sequence("orderNo", 1000, 1))
.addFeeder(LoadTestFeeder.random("qty", 1, 5))
.addFeeder(LoadTestFeeder.constant("channel", "web"))
.step("Order")
.post("/api/${region}/orders")
.body(Map.of("sku", "${sku}", "qty", "${qty}", "no", "${orderNo}", "channel", "${channel}"))
.and()
.run();
}

XPath, JMESPath, HEAD and OPTIONS checks​

Besides status and JSONPath, a step can check and extract with XPath, JMESPath and response headers, and send HEAD and OPTIONS requests. A HEAD step accepts only status and header checks. On the JDK engine JMESPath is a subset (a.b, a[0].b, quoted keys, indexes); filters, projections and functions are rejected before any request, while Gatling supports full JMESPath. warehouses[0].name is inside the subset. See Response checks per source, JMESPath on each engine and HEAD and OPTIONS steps.

@Test
public void correlationAndChecks() {
loadScenario("Checks")
.users(10)
.step("SOAP-ish XML")
.post("/api/legacy/quote")
.header("Content-Type", "application/xml")
.body("<quoteRequest><sku>ABC</sku></quoteRequest>")
.check(xpath("/quote/price").exists())
.extract("price", xpath("/quote/price"))
.and()
.step("JMESPath")
.get("/api/inventory")
.check(jmesPath("warehouses[0].name").is("IST"))
.and()
.step("HEAD")
.head("/static/app.js")
.check(headerPresent("Cache-Control"))
.and()
.step("CORS preflight")
.options("/api/cart")
.check(responseHeader("Access-Control-Allow-Methods").matches(".*POST.*"))
.and()
.run()
.assertNoStatus(500);
}

Authentication​

A scenario-level OAuth2 client-credentials token is fetched once per run, before the load, and refreshed in the background. A step can opt out with noAuth() or override it with its own basicAuth(..), whose ${user} is resolved per request from the feeder. LoadAuth.fromConfig(name) reuses an api.auth.<name> entry of testfly.yml (types basic, bearer, oauth2). Read secrets from the environment. See Authentication, Precedence, OAuth2 client credentials and fromConfig.

@Test
public void authenticated() {
loadScenario("Auth - OAuth2")
.users(100)
.auth(LoadAuth.oauth2ClientCredentials(
"https://auth.example.com/oauth2/token",
System.getenv("CLIENT_ID"),
System.getenv("CLIENT_SECRET"))
.scope("orders.read"))
.step("Orders").get("/api/orders").and()
.step("Public health").get("/api/health").noAuth().and() // no token sent
.step("Legacy basic").get("/legacy/report")
.basicAuth("${user}", System.getenv("LEGACY_PASSWORD")).and() // step override
.feed(LoadTestFeeder.csv("data/legacy-users.csv"))
.run()
.assertErrorRateBelow(0.01);
}

@Test
public void authFromConfig() {
loadScenario("Auth - from testfly.yml")
.auth(LoadAuth.fromConfig("partnerApi")) // api.auth.partnerApi (basic | bearer | oauth2)
.step("Partner").get("/partner/v1/items").and()
.run();
}

Multi-scenario simulation with SLA​

Gatling only. loadSimulation(..) runs several scenarios, each with its own workload, in one run. SLAs can be attached to a scenario (with plain step names) and to the simulation (evaluated against the global metrics); if any rule fails, run() throws one AssertionError listing every failed rule. See Simulations and SLAs.

@Test
public void mixedTrafficSimulation() {
LoadScenario browsers = loadScenario("Browsers")
.workload(Workload.open(constantRate(30, Duration.ofMinutes(5))))
.step("Home").get("/").and()
.sla(LoadSla.sla().p95Below(300).step("Home").p99Below(800));

LoadScenario buyers = loadScenario("Buyers")
.workload(Workload.closed(constantConcurrent(20, Duration.ofMinutes(5))))
.step("Checkout").post("/api/checkout").and()
.sla(LoadSla.sla().errorRateBelow(0.001));

LoadSimulationResult result = loadSimulation("Black Friday")
.scenario(browsers)
.scenario(buyers)
.sla(LoadSla.sla()
.p95Below(500)
.p99Below(1200)
.errorRateBelow(0.01)
.throughputAbove(40))
.run();

result.global().assertSlaPassed();
result.scenario("Buyers").assertP95Below(700);
}

Baseline and regression​

The first run saves its metrics as a baseline file; later runs compare against it. Tolerance.percent(10) allows p95, p99 and mean to grow, and throughput to drop, by 10%; errorRateDelta(0.005) allows the error rate to rise by 0.005 (half a percentage point). Partial metrics never become a baseline. See Baseline comparison.

@Test
public void noRegressionAgainstBaseline() {
Path baselineFile = Path.of("src/test/resources/baselines/catalog.json");

LoadTestAssert run = loadScenario("Catalog")
.users(100)
.step("Catalog").get("/api/catalog").and()
.run();

if (!baselineFile.toFile().exists()) {
LoadBaseline.of(run.metrics()).save(baselineFile); // first run: create the baseline
return;
}
run.assertNoRegression(LoadBaseline.load(baselineFile),
Tolerance.percent(10).errorRateDelta(0.005)); // latency and throughput 10%, error rate +0.005
}

JDK engine​

The JDK engine needs no Gatling dependency and runs the same DSL in the test JVM. It does not support workloads or simulations, and it accepts only the JMESPath subset described above. A method-level @LoadTest overrides the class-level values. See Engines.

@Test
@LoadTest(engine = "jdk", users = 20, hold = "30s")
public void jdkEngine() {
load("/api/ping").run().assertSuccessRateAbove(0.99);
}

Proxy, TLS, retention and the Gatling JVM in testfly.yml​

These blocks are read from testfly.yml only; @LoadTest and LoadScenario have no setting for them. proxy, tls and retention apply to both engines, gatling to the forked Gatling child JVM only. Keep passwords in ${ENV} placeholders. See Proxy, TLS, Run retention and Gatling child JVM.

loadtest:
retention: # run directories in resultsDir, swept after every run (both engines)
runs: 10 # keep the newest 10 of the scenario that just ran; 0 = keep all (default)
maxAgeDays: 14 # delete TestFly run directories older than 14 days; 0 = no limit (default)
gatling: # the forked Gatling child JVM (Gatling engine only)
maxHeap: 1g # -Xmx1g; "50%" gives -XX:MaxRAMPercentage=50; unset = JVM default (default)
jvmArgs: # one JVM option per element, checked against an allowlist when a run starts
- "-XX:+UseG1GC"
- "-XX:+HeapDumpOnOutOfMemoryError"
maxParallelRuns: 2 # Gatling runs at once in this JVM, 1..16; 1 = one at a time (default)
proxy: # HTTP proxy for load and OAuth2 token requests (both engines); unset = see below
host: proxy.corp.example
port: 3128
username: ${LOAD_PROXY_USER}
password: ${LOAD_PROXY_PASSWORD}
nonProxyHosts: [localhost, "*.internal.example"]
tls: # trust and client stores (both engines); unset = each engine's default
trustStore: { path: certs/load-trust.p12, password: ${LOAD_TRUSTSTORE_PASSWORD} } # type: PKCS12 (default) | JKS
keyStore: { path: certs/load-client.p12, password: ${LOAD_KEYSTORE_PASSWORD} } # mTLS
insecureTrustAll: false # trust any server certificate (hostname still verified)

When proxy or tls is unset, the engines differ: for example, Gatling trusts every certificate without a hostname check, while the JDK engine verifies both. See Engine differences.