### Example Usage of JMeter Java DSL Builders
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/CONTRIBUTING.md
Illustrates common patterns for using DSL elements in code. This includes examples of creating elements with names and required properties, adding optional configurations, specifying children elements, and creating elements with just required properties. The examples demonstrate the fluent API style facilitated by the DSL.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
// Example 1: Element with name, required property, optional property, and children
httpSampler("My Sampler", "http://example.com")
.contentType("application/json")
.children(
httpHeader("Authorization", "Bearer token")
);
// Example 2: Element with required property and children
jdbcConnection("jdbc:mysql://localhost:3306/mydb", "user", "password")
.children(
jdbcRequest("SELECT * FROM users")
);
// Example 3: Element with required property and a single child
loopController(10, httpSampler("Another Sampler", "http://test.com"));
// Example 4: Element with name, required property, and a single child
transactionController("My Transaction", 5, httpSampler("Child Sampler", "http://child.com"));
```
--------------------------------
### Basic HTTP GET and POST Samplers in Java
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/protocols/http/methods-and-body.md
Demonstrates how to create simple HTTP GET and POST requests using the httpSampler function. The POST example shows how to specify a JSON body and content type.
```java
httpSampler("http://my.service") // A simple get
httpSampler("http://my.service")
.post("{\"field\":\"val\"}", Type.APPLICATION_JSON) // simple post
```
--------------------------------
### Setup and Teardown Thread Groups in Java
Source: https://context7.com/abstracta/jmeter-java-dsl/llms.txt
Illustrates how to use setup and teardown thread groups with the JMeter Java DSL. Setup thread groups execute before the main test, ideal for initialization tasks, while teardown thread groups run after the main test, suitable for cleanup operations. This ensures a controlled test environment.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import org.apache.http.entity.ContentType;
public class SetupTeardownExample {
public void testWithSetupAndTeardown() throws Exception {
testPlan(
// Runs before all other thread groups
setupThreadGroup(
httpSampler("http://my.service/api/test-data/create")
.post("{\"scenario\":\"load-test\"}", ContentType.APPLICATION_JSON)
),
// Main test thread group
threadGroup(10, Duration.ofMinutes(5),
httpSampler("http://my.service/api/users")
),
// Runs after all other thread groups complete
teardownThreadGroup(
httpSampler("http://my.service/api/test-data/cleanup")
.method("DELETE")
)
).run();
}
}
```
--------------------------------
### Make Simple and Parameterized GraphQL Requests in Java
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/protocols/graphql.md
This Java code demonstrates how to use the graphqlSampler from jmeter-java-dsl to send GraphQL requests. It shows examples of both simple queries and queries with operation names and variables.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import static us.abstracta.jmeter.javadsl.graphql.DslGraphqlSampler.*;
import org.junit.jupiter.api.Test;
public class PerformanceTest {
@Test
public void test() throws Exception {
String url = "https://myservice.com";
testPlan(
threadGroup(1, 1,
graphqlSampler(url, "{user(id: 1) {name}}"),
graphqlSampler(url, "query UserQuery($id: Int) { user(id: $id) {name}}")
.operationName("UserQuery")
.variable("id", 2)
)
).run();
}
}
```
--------------------------------
### Create HTTP GET and POST Requests with JMeter Java DSL
Source: https://context7.com/abstracta/jmeter-java-dsl/llms.txt
Demonstrates how to create HTTP GET and POST requests using the httpSampler() method. Supports various methods, headers, bodies, and content types. No external dependencies beyond the DSL itself.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import org.apache.http.entity.ContentType;
import org.apache.jmeter.protocol.http.util.HTTPConstants;
public class HttpSamplerExamples {
public void examples() throws Exception {
testPlan(
threadGroup(1, 1,
// Simple GET request
httpSampler("http://my.service/users"),
// POST with JSON body
httpSampler("http://my.service/users")
.post("{\"name\": \"John\", \"email\": \"john@example.com\"}", ContentType.APPLICATION_JSON),
// PUT request with custom method and body
httpSampler("http://my.service/users/1")
.method(HTTPConstants.PUT)
.contentType(ContentType.APPLICATION_JSON)
.body("{\"name\": \"John Updated\"}"),
// Named sampler for clear reporting
httpSampler("CreateUser", "http://my.service/users")
.post("{\"name\": \"Jane\"}", ContentType.APPLICATION_JSON)
)
).run();
}
}
```
--------------------------------
### Get JMeter DSL Recorder Help
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/recorder/index.md
This command displays the available options and usage instructions for the JMeter DSL recorder. It helps in customizing the recording process.
```bash
java -jar jmdsl.jar help recorder
```
--------------------------------
### Get Test Jar and Libs Files for JMeter
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/response-processing/lambdas.md
This Java code snippet retrieves the test jar path and lists all files in the 'target/libs' directory. It then creates an array containing the test jar and all files from the libs directory, suitable for use with JMeter.
```java
File[] libsFiles = new File("target/libs").listFiles();
File[] ret = new File[libsFiles.length + 1];
ret[0] = new File(System.getProperty("testJar.path"));
System.arraycopy(libsFiles, 0, ret, 1, libsFiles.length);
return ret;
```
--------------------------------
### Create JMeter Test Plan with Java DSL
Source: https://context7.com/abstracta/jmeter-java-dsl/llms.txt
Demonstrates the basic structure of creating a JMeter test plan using the Java DSL. It includes setting up a thread group, an HTTP sampler, and a JTL writer for reporting. The example also shows how to assert on test statistics like sample time and errors.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws Exception {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
.post("{\"name\": \"test\"}", org.apache.http.entity.ContentType.APPLICATION_JSON)
),
jtlWriter("target/jtls")
).run();
// Assert on collected statistics
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
assertThat(stats.overall().errorsCount()).isEqualTo(0);
}
}
```
--------------------------------
### Execute Setup and Teardown Logic within JMeter Context
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/thread-groups/setup-and-teardown.md
Illustrates using `setupThreadGroup` and `teardownThreadGroup` to execute logic within the JMeter execution context. This is useful for setting JMeter properties or performing actions on the same host where the test plan runs, like token management.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import java.time.Duration;
import org.apache.jmeter.protocol.http.util.HTTPConstants;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws IOException {
TestPlanStats stats = testPlan(
setupThreadGroup(
httpSampler("http://my.service/tokens")
.method(HTTPConstants.POST)
.children(
jsr223PostProcessor("props.put('MY_TEST_TOKEN', prev.responseDataAsString)")
)
),
threadGroup(2, 10,
httpSampler("http://my.service/products")
.header("X-MY-TOKEN", "${__P(MY_TEST_TOKEN)}")
),
teardownThreadGroup(
httpSampler("http://my.service/tokens/${__P(MY_TEST_TOKEN)}")
.method(HTTPConstants.DELETE)
)
).run();
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Run JMeter Test Plan on BlazeMeter
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/scale/blazemeter.md
Example Java code demonstrating how to execute a JMeter test plan using the BlazeMeterEngine, configuring test name, total users, hold duration, threads per engine, and test timeout. It also shows how to assert test results.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.blazemeter.BlazeMeterEngine;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws Exception {
TestPlanStats stats = testPlan(
// number of threads and iterations are in the end overwritten by BlazeMeter engine settings
threadGroup(2, 10,
httpSampler("http://my.service")
)
).runIn(new BlazeMeterEngine(System.getenv("BZ_TOKEN"))
.testName("DSL test")
.totalUsers(500)
.holdFor(Duration.ofMinutes(10))
.threadsPerEngine(100)
.testTimeout(Duration.ofMinutes(20)));
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Custom Redis Sampler Class with Thread Listeners (Java DSL)
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/protocols/java.md
This example defines a custom Java class `RedisSampler` that implements `SamplerScript` and `ThreadListener` to manage Redis connections and operations. It allows executing logic at thread start, during script execution, and at thread finish, providing a structured approach for complex scenarios.
```java
public class TestRedis {
public static class RedisSampler implements SamplerScript, ThreadListener {
private Jedis jedis;
@Override
public void threadStarted() {
jedis = new Jedis("localhost", 6379);
jedis.connect();
}
@Override
public void runScript(SamplerVars v) {
jedis.set("foo", "bar");
v.sampleResult.setResponseData(jedis.get("foo"), StandardCharsets.UTF_8.name());
}
@Override
public void threadFinished() {
jedis.close();
}
}
@Test
public void shouldGetExpectedSampleResultWhenJsr223SamplerWithLambdaAndCustomResponse()
throws IOException {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
jsr223Sampler(RedisSampler.class)
)
).run();
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofMillis(500));
}
}
```
--------------------------------
### Basic Prometheus Listener Setup in JMeter Java DSL Test
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/reporting/real-time/prometheus.md
This Java code demonstrates how to include the `prometheusListener()` in your JMeter test plan. It configures a simple test with HTTP samplers and enables Prometheus metrics collection.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import static us.abstracta.jmeter.javadsl.prometheus.DslPrometheusListener.*;
import java.io.IOException;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws IOException {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
),
prometheusListener()
).run();
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Run Custom Logic Before/After JMeter Test with JUnit
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/thread-groups/setup-and-teardown.md
Demonstrates how to use JUnit's `@BeforeEach` and `@AfterEach` annotations to execute custom Java logic before and after a JMeter test. This approach is suitable for simple setup and teardown tasks not requiring JMeter's execution context.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@BeforeEach
public void setup() {
// my custom setup logic
}
@AfterEach
public void setup() {
// my custom setup logic
}
@Test
public void testPerformance() throws IOException {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
)
).run();
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Iterate While Condition Met with Java Lambda
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/request-generation/loops/while-controller.md
Shows how to use the whileController with a Java lambda for the condition, providing IDE auto-completion and type safety. This example also includes an HTTP sampler and regex extractor.
```java
whileController(s -> s.vars.get("ACCOUNT_ID") == null,
httpSampler("http://my.service/accounts")
.post("{\"name\": \"John Doe\"}", Type.APPLICATION_JSON)
.children(
regexExtractor("ACCOUNT_ID", "\"id\":\"([^\"]+)\"")
)
)
```
--------------------------------
### Include jmeter-java-dsl Dependency (Maven/Gradle)
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/setup.md
This snippet shows how to add the jmeter-java-dsl to your project's dependencies. For Maven, it's a standard dependency declaration. For Gradle, it uses the testImplementation configuration and excludes the BOM to avoid version conflicts.
```xml
us.abstracta.jmeter
jmeter-java-dsl
2.2
test
```
```groovy
testImplementation("us.abstracta.jmeter:jmeter-java-dsl:2.2") {
exclude("org.apache.jmeter", "bom")
}
```
--------------------------------
### Automatic File Uploads with Azure Engine
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/scale/azure.md
Demonstrates how AzureEngine automatically uploads files referenced by csvDataSet and httpSampler (with bodyFile or bodyFilePart) to Azure Load Testing, simplifying test setup.
```java
testPlan(
threadGroup(100, Duration.ofMinutes(5),
csvDataSet(new TestResource("users.csv")),
httpSampler(SAMPLE_LABEL, "https://myservice/users/${USER}")
)
).runIn(new AzureEngine(System.getenv("BZ_TOKEN"))
.testTimeout(Duration.ofMinutes(10)));
```
--------------------------------
### Run JMeter Test with CSV Data and BlazeMeter
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/scale/blazemeter.md
Example Java code showing how to run a JMeter test plan that uses a CSV data set and an HTTP sampler, integrated with BlazeMeter. It demonstrates automatic uploading of referenced files and setting a test timeout.
```java
testPlan(
threadGroup(100, Duration.ofMinutes(5),
csvDataSet(new TestResource("users.csv")),
httpSampler(SAMPLE_LABEL, "https://myservice/users/${USER}")
)
).runIn(new BlazeMeterEngine(System.getenv("BZ_TOKEN"))
.testTimeout(Duration.ofMinutes(10)));
```
--------------------------------
### Replace Lambdas with Static Classes in JMeter Java DSL (Java)
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/response-processing/lambdas.md
Demonstrates how to refactor Java lambdas used in JMeter Java DSL test plans into public static classes that implement specific script interfaces. This is necessary for remote execution with BlazeMeterEngine. The example shows converting a JSR223 PostProcessor lambda to a static class implementing `PostProcessorScript`.
```java
public class PerformanceTest {
@Test
public void testPerformance() throws Exception {
testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
.children(
jsr223PostProcessor(s -> {
if ("429".equals(s.prev.getResponseCode())) {
s.prev.setSuccessful(true);
}
})
)
)
).runIn(new BlazeMeterEngine(System.getenv("BZ_TOKEN")));
}
}
```
```java
public class PerformanceTest {
public static class StatusSuccessProcessor implements PostProcessorScript {
@Override
public void runScript(PostProcessorVars s) {
if ("429".equals(s.prev.getResponseCode())) {
s.prev.setSuccessful(true);
}
}
}
@Test
public void testPerformance() throws Exception {
testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
.children(
jsr223PostProcessor(StatusSuccessProcessor.class)
)
)
).runIn(new BlazeMeterEngine(System.getenv("BZ_TOKEN")));
}
}
```
--------------------------------
### Modularize Test Plan with Methods using Controllers in Java DSL
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/request-generation/group-requests.md
This snippet demonstrates how to modularize a JMeter test plan by creating reusable Java methods for common test flows, such as login and adding items to the cart. These methods return JMeter DSL controllers (Transaction or Simple), promoting code reusability and maintainability. The example defines methods for 'login' and 'addItemToCart' and then uses them within the main test plan.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import org.apache.http.entity.ContentType;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.controllers.DslTransactionController;
public class PerformanceTest {
private DslTransactionController login(String baseUrl) {
return transaction("login",
httpSampler(baseUrl),
httpSampler(baseUrl + "/login")
.post("user=test&password=test", ContentType.APPLICATION_FORM_URLENCODED)
);
}
private DslTransactionController addItemToCart(String baseUrl) {
return transaction("addItemToCart",
httpSampler(baseUrl + "/items"),
httpSampler(baseUrl + "/cart/items")
.post("{\"id\": 1}", ContentType.APPLICATION_JSON)
);
}
@Test
public void testTransactions() throws IOException {
String baseUrl = "http://my.service";
testPlan(
threadGroup(2, 10,
login(baseUrl),
addItemToCart(baseUrl)
)
).run();
}
}
```
--------------------------------
### Configure BlazeMeterEngine for Asset Upload (Java)
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/response-processing/lambdas.md
Illustrates how to configure the `BlazeMeterEngine` to upload test assets, such as the generated test JAR and its dependencies. This involves renaming the test class to include the 'IT' suffix and using the `.assets(findAssets())` method to specify the files to be uploaded.
```java
// Here we renamed from PerformanceTest to PerformanceIT
public class PerformanceIT {
...
@Test
public void testPerformance() throws Exception {
testPlan(
...
).runIn(new BlazeMeterEngine(System.getenv("BZ_TOKEN"))
.assets(findAssets()));
}
private File[] findAssets() {
```
--------------------------------
### Implementing DSL Builder Methods in JMeter Java DSL
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/CONTRIBUTING.md
Details the implementation of static public builder/factory methods for new DSL test elements, enabling easy usage in DSL test plans via static imports. Builder methods should be short, descriptive, and use nouns. They should include Javadoc explaining their purpose and linking to the DslTestElement. Builders should be provided for each required parameter combination. If the element name is meaningful, a builder method with the name as the first parameter can be offered. Container elements should have builders accepting var args of children. Optional configurations can be handled by methods on the DslTestElement class.
```java
/**
* Creates a new HTTP sampler with the given name and URL.
* @param name The name of the sampler.
* @param url The URL to send the request to.
* @return A new DslHttpSampler instance.
*/
public static DslHttpSampler httpSampler(String name, String url) {
return new DslHttpSampler(name, url);
}
/**
* Creates a new HTTP sampler with the given URL.
* @param url The URL to send the request to.
* @return A new DslHttpSampler instance.
*/
public static DslHttpSampler httpSampler(String url) {
return new DslHttpSampler(url);
}
// Example of a builder for a container element
/**
* Creates a new parallel controller with the given children elements.
* @param children The child elements to include in the parallel controller.
* @return A new ParallelController instance.
*/
public static ParallelController parallel(DslTestElement... children) {
return new ParallelController(children);
}
```
--------------------------------
### Maven Configuration for JMeter Java DSL Tests (XML)
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/response-processing/lambdas.md
Provides a Maven configuration snippet to set up the build process for JMeter Java DSL tests. It includes plugins for generating a test JAR, copying dependencies, and executing integration tests. This configuration is essential for packaging and running tests remotely with BlazeMeterEngine.
```xml
...
org.apache.maven.plugins
maven-jar-plugin
3.3.0
test-jar
org.apache.maven.plugins
maven-dependency-plugin
3.6.0
copy-dependencies
package
copy-dependencies
${project.build.directory}/libs
jmeter-java-dsl
org.apache.maven.plugins
maven-failsafe-plugin
3.0.0-M7
${project.build.directory}/${project.artifactId}-${project.version}-tests.jar
integration-test
verify
```
--------------------------------
### Basic WebSocket Test Plan with JMeter Java DSL
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/protocols/websocket.md
This Java code illustrates a basic JMeter test plan using the WebSocket DSL. It sets up a thread group, establishes a WebSocket connection, sends a message, reads a response with an assertion, and then disconnects. It requires the JMeter Java DSL and WebSocket sampler dependencies.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import static us.abstracta.jmeter.javadsl.websocket.WebsocketJMeterDsl.*;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class Test {
public static void main(String[] args) throws Exception {
TestPlanStats stats = testPlan(
threadGroup(1, 1,
websocketConnect("wss://ws.postman-echo.com/raw"),
websocketWrite("Hello WebSocket!"),
websocketRead()
.children(
responseAssertion()
.equalsToStrings("Hello WebSocket!")
),
websocketDisconnect()
)
).run();
}
}
```
--------------------------------
### Configure Auto-Incremental Counter in Java DSL
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/request-generation/counter.md
Demonstrates how to use the `counter` configuration to generate unique, auto-incremental values for use in HTTP requests. This is particularly useful for parameters like user IDs. The counter can be initialized with a starting value.
```java
testPlan(
threadGroup(1, 10,
counter("USER_ID")
.startingValue(1000), // will generate 1000, 1001, 1002...
httpSampler(wiremockUri + "/${USER_ID}")
)
).run();
```
--------------------------------
### Configure BlazeMeter Test Locations
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/scale/blazemeter.md
Example Java code illustrating how to configure multiple execution locations for a JMeter test on BlazeMeter, distributing users across different regions like GCP Sao Paulo and a private location. Includes setting a test timeout.
```java
testPlan(
threadGroup(300, Duration.ofMinutes(5), // 300 total users for 5 minutes
httpSampler(SAMPLE_LABEL, "https://myservice")
)
).runIn(new BlazeMeterEngine(System.getenv("BZ_TOKEN"))
.location(BlazeMeterLocation.GCP_SAO_PAULO, 30) // 30% = 90 users will run in Google Cloud Platform at Sao Paulo
.location("MyPrivateLocation", 70) // 70% = 210 users will run in MyPrivateLocation named private location
.testTimeout(Duration.ofMinutes(10)));
```
--------------------------------
### Execute Test Plan Sections Probabilistically with Percent Controller in Java
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/request-generation/percent-controller.md
This Java code demonstrates how to use the Percent Controller to execute specific parts of a JMeter test plan a given percentage of times. It requires the JMeter Java DSL library. The input is a test plan configuration, and the output is a TestPlanStats object.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws Exception {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
percentController(40, // run this 40% of the times
httpSampler("http://my.service/status"),
httpSampler("http://my.service/poll")),
percentController(70, // run this 70% of the times
httpSampler("http://my.service/items"))
)
).run();
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Execute Once Only Controller in Java DSL
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/request-generation/loops/once-only-controller.md
Demonstrates how to use the `onceOnlyController` to execute a block of samplers only once per thread. This example includes an HTTP sampler for login that runs once, followed by another HTTP sampler for accounts that runs for each iteration, using a token extracted from the first sampler.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import org.apache.jmeter.protocol.http.util.HTTPConstants;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.JmeterDslTest;
public class DslOnceOnlyControllerTest extends JmeterDslTest {
@Test
public void shouldExecuteOnlyOneTimeWhenOnceOnlyControllerInPlan() throws Exception {
testPlan(
threadGroup(1, 10,
onceOnlyController(
httpSampler("http://my.service/login") // only runs once
.method(HTTPConstants.POST)
.header("Authorization", "Basic asdf=")
.children(
regexExtractor("AUTH_TOKEN", "authToken=(.*)")
)
),
httpSampler("http://my.service/accounts") // runs ten times
.header("Authorization", "Bearer ${AUTH_TOKEN}")
)
).run();
}
}
```
--------------------------------
### Custom HTTP Method and Body Configuration in Java
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/protocols/http/methods-and-body.md
Illustrates how to configure an HTTP sampler with a custom method (e.g., PUT), content type, and a static request body. This provides more control over the HTTP request.
```java
httpSampler("http://my.service")
.method(HTTPConstants.PUT)
.contentType(Type.APPLICATION_JSON)
.body("{\"field\":\"val\"}")
```
--------------------------------
### Configure Thread Ramp-Up and Hold Times with Java DSL
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/thread-groups/ramps-and-holds.md
Demonstrates how to set up thread ramp-up periods and holding iterations using the JMeter Java DSL. This helps in gradually increasing threads to avoid performance metric distortions. It shows basic ramp-to and hold-iterating configurations.
```java
threadGroup().rampTo(10, Duration.ofSeconds(5)).holdIterating(20) // ramp to 10 threads for 5 seconds (1 thread every half second) and iterating each thread 20 times
threadGroup().rampToAndHold(10, Duration.ofSeconds(5), Duration.ofSeconds(20)) //similar as above but after ramping up holding execution for 20 seconds
```
--------------------------------
### Example JMeter Java DSL Test Plan
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/jmx2dsl.md
This Java code snippet demonstrates a basic JMeter test plan generated by the `jmx2dsl` tool. It includes a thread group with an HTTP sampler and a JTL writer. This code can be executed using Jbang.
```java
///usr/bin/env jbang "$0" "$@" ; exit $?
/*
These commented lines make the class executable if you have jbang installed by making the file
executable (eg: chmod +x ./PerformanceTest.java) and just executing it with ./PerformanceTest.java
*/
//DEPS org.assertj:assertj-core:3.23.1
//DEPS org.junit.jupiter:junit-jupiter-engine:5.9.1
//DEPS org.junit.platform:junit-platform-launcher:1.9.1
//DEPS us.abstracta.jmeter:jmeter-java-dsl:2.2
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import java.io.PrintWriter;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
import org.junit.platform.launcher.listeners.TestExecutionSummary;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void test() throws IOException {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
),
jtlWriter("target/jtls")
).run();
assertThat(stats.overall().errorsCount()).isEqualTo(0);
}
/*
This method is only included to make the test class self-executable. You can remove it when
executing tests with maven, gradle, or some other tool.
*/
public static void main(String[] args) {
SummaryGeneratingListener summaryListener = new SummaryGeneratingListener();
LauncherFactory.create()
.execute(LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectClass(PerformanceTest.class))
.build(),
summaryListener);
TestExecutionSummary summary = summaryListener.getSummary();
summary.printFailuresTo(new PrintWriter(System.err));
System.exit(summary.getTotalFailureCount() > 0 ? 1 : 0);
}
}
```
--------------------------------
### Configure HTTP Defaults and Headers with JMeter Java DSL
Source: https://context7.com/abstracta/jmeter-java-dsl/llms.txt
Shows how to set default base URLs, connection timeouts, and response timeouts using httpDefaults(). Also demonstrates applying common headers like Authorization and X-Request-ID to multiple samplers using httpHeaders().
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
public class HttpConfigExamples {
public void examples() throws Exception {
testPlan(
// Set default base URL and connection settings for all HTTP samplers
httpDefaults()
.url("http://my.service")
.connectionTimeout(Duration.ofSeconds(5))
.responseTimeout(Duration.ofSeconds(30)),
threadGroup(5, 10,
// Headers applied to all samplers in scope
httpHeaders()
.header("Authorization", "Bearer ${TOKEN}")
.header("X-Request-ID", "${__UUID}"),
httpSampler("/api/users"), // Uses base URL from defaults
httpSampler("/api/products"),
httpSampler("/api/orders")
)
).run();
}
}
```
--------------------------------
### Basic JMeter Test Plan with HTTP POST in Java DSL
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/README.md
This Java code demonstrates a basic performance test using the jmeter-java-dsl. It sets up a test plan with a thread group of 2 users iterating 10 times, sending an HTTP POST request with a JSON body to a specified URL. It also includes a JTL writer for logging and an assertion to check the 99th percentile of sample time.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import org.apache.http.entity.ContentType;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws IOException {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
.post("{\"name\": \"test\"}", ContentType.APPLICATION_JSON)
),
//this is just to log details of each request stats
jtlWriter("target/jtls")
).run();
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Simulate HTTP Sampler with Dummy Sampler in Java
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/debugging/dummy-sampler.md
This Java code demonstrates how to use the dummySampler to simulate HTTP requests within a JMeter test plan. It's useful for testing components like JSON extractors and forEach controllers without actual server interaction. The dummySampler can be configured with a response body and URL.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import org.junit.jupiter.api.Test;
public class PerformanceTest {
@Test
public void testPerformance() throws IOException {
String usersIdVarName = "USER_IDS";
String userIdVarName = "USER_ID";
String usersPath = "/users";
testPlan(
httpDefaults().url("http://my.service"),
threadGroup(1, 1,
// httpSampler(usersPath) // Commented out original sampler
dummySampler("[{\"id\": 1, \"name\": \"John\"}, {\"id\": 2, \"name\": \"Jane\"}]")
.children(
jsonExtractor(usersIdVarName, "[].id")
.matchNumber(-1)
),
forEachController(usersIdVarName, userIdVarName,
// httpSampler(usersPath + "/${" + userIdVarName + "}") // Commented out original sampler
dummySampler("{\"name\": \"John or Jane\"}")
.url("http://my.service/" + usersPath + "/${" + userIdVarName + "}")
)
),
resultsTreeVisualizer()
).run();
}
}
```
--------------------------------
### Run JMeter Test Plan at Scale with OctoPerf
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/scale/octoperf.md
Execute a JMeter test plan using the OctoPerf engine by providing your OctoPerf API key and configuring test parameters like project name, total users, ramp-up, and hold duration. This example demonstrates a basic HTTP sampler test.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.octoperf.OctoPerfEngine;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws Exception {
TestPlanStats stats = testPlan(
// number of threads and iterations are in the end overwritten by OctoPerf engine settings
threadGroup(2, 10,
httpSampler("http://my.service")
)
).runIn(new OctoPerfEngine(System.getenv("OCTOPERF_API_KEY"))
.projectName("DSL test")
.totalUsers(500)
.rampUpFor(Duration.ofMinutes(1))
.holdFor(Duration.ofMinutes(10))
.testTimeout(Duration.ofMinutes(20)));
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Display JMeter Test Plan in GUI using Java DSL
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/debugging/show-in-gui.md
This Java code snippet demonstrates how to generate a JMeter test plan using the JMeter Java DSL and then display it in the JMeter GUI. It requires the JMeter Java DSL library. The `showInGui()` method is called on the test plan object to open the GUI.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import org.junit.jupiter.api.Test;
public class PerformanceTest {
@Test
public void testPerformance() throws IOException {
testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
)
).showInGui();
}
}
```
--------------------------------
### Generate JMeter Java DSL from JMX using jmx2dsl CLI
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/jmx2dsl.md
The `jmx2dsl` command-line tool generates JMeter Java DSL code from JMX files. It can be executed directly using a JAR file or via Jbang. Ensure you have Java 11 or newer installed to run this tool.
```bash
java -jar jmdsl.jar jmx2dsl test-plan.jmx
```
```bash
jbang us.abstracta.jmeter:jmeter-java-dsl-cli:2.2 jmx2dsl test-plan.jmx
```
--------------------------------
### Create Custom HTTP Sampler Builder Method
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/protocols/http/defaults.md
Illustrates creating a custom Java method (`productCreatorSampler`) to encapsulate repetitive HTTP sampler configurations, such as the base URL and content type. This approach enhances code readability and maintainability by abstracting common sampler details.
```java
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import org.apache.http.entity.ContentType;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.http.DslHttpSampler;
public class PerformanceTest {
@Test
public void performanceTest() throws IOException {
String host = "myservice.my";
testPlan(
threadGroup(10, 100,
productCreatorSampler(host, "Rubber"),
productCreatorSampler(host, "Pencil")
)
).run();
}
private DslHttpSampler productCreatorSampler(String host, String productName) {
return httpSampler("https://" + host + "/api/product")
.post("{\"name\": \"" + productName + "\"}", ContentType.APPLICATION_JSON);
}
}
```
--------------------------------
### Implement Probabilistic Test Plan Branching with WeightedSwitchController in Java
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/request-generation/weighted-switch-controller.md
This Java code snippet demonstrates the usage of the weightedSwitchController to distribute iterations among different HTTP samplers based on defined probabilities. It requires the JMeter Java DSL library. The input is a JMeter test plan configuration, and the output is a TestPlanStats object containing performance metrics.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws IOException {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
weightedSwitchController()
.child(30, httpSampler("https://myservice/1")) // will run 30/(30+20)=60% of the iterations
.child(20, httpSampler("https://myservice/2")) // will run 20/(30+20)=40% of the iterations
)
).run();
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Control Loop Duration with RuntimeController in Java
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/request-generation/loops/runtime-controller.md
This Java code demonstrates how to use runtimeController to limit the execution of child elements within a JMeter thread group for a specified duration. It's useful for scenarios where you need to stop requests after a certain time, like token expiration. This example uses httpSampler and whileController.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws IOException {
Duration tokenExpiration = Duration.ofSeconds(5);
TestPlanStats stats = testPlan(
threadGroup(2, 10,
httpSampler("http://my.service/token"),
runtimeController(tokenExpiration,
whileController("true",
httpSampler("http://my.service/accounts")
)
)
)
).run();
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Generate HTTP Requests with JMeter Java DSL
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/simple-test-plan.md
This Java code snippet demonstrates how to create a simple JMeter test plan using the Java DSL. It configures a thread group with a specified number of threads and iterations, defines an HTTP sampler to send requests to a target URL, and includes a JTL writer for logging test results. It also asserts that the 99th percentile of sample times is less than 5 seconds.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws IOException {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
),
//this is just to log details of each request stats
jtlWriter("target/jtls")
).run();
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Generate HTML Report from JMeter Test Plan Execution (Java)
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/reporting/html-reporter.md
This code snippet demonstrates how to configure and run a JMeter test plan using the Java DSL, including the generation of an HTML report. It utilizes the `htmlReporter` to output the report to a specified directory. The example assumes the `jmeter-java-dsl` and `assertj-core` libraries are available.
```java
import static org.assertj.core.api.Assertions.assertThat;
import static us.abstracta.jmeter.javadsl.JmeterDsl.*;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;
public class PerformanceTest {
@Test
public void testPerformance() throws IOException {
TestPlanStats stats = testPlan(
threadGroup(2, 10,
httpSampler("http://my.service")
),
htmlReporter("reports")
).run();
assertThat(stats.overall().sampleTimePercentile99()).isLessThan(Duration.ofSeconds(5));
}
}
```
--------------------------------
### Set HTTP Connection and Response Timeouts with Java DSL
Source: https://github.com/abstracta/jmeter-java-dsl/blob/master/docs/guide/protocols/http/timeouts.md
Configures the default HTTP request settings to specify connection and response timeouts. This ensures that JMeter tests behave consistently regardless of the underlying system's default network configurations. The example sets a connection timeout of 10 seconds and a response timeout of 1 minute.
```java
testPlan(
httpDefaults()
.connectionTimeout(Duration.ofSeconds(10))
.responseTimeout(Duration.ofMinutes(1)),
threadGroup(2, 10,
httpSampler("http://my.service")
)
)
```