Generate Dynamic API Tests With REST Assured
Generate tests at run time with JUnit's @TestFactory, so every endpoint in a list gets the same security checks, and group them per endpoint with dynamicContainer.
Every endpoint of the payments API must reject a request without a token. That’s one parameterized test with a row per endpoint. Then you add a second check, a wrong token, and a third, Basic credentials instead of a bearer token. Now it’s three parameterized tests with the same six rows, or one test that does three checks and stops at the first failure. Neither fits. What you want is a list of endpoints and a list of checks, and every combination as its own test, named and grouped in the report. In this guide, you’ll generate those tests at run time.
Level: Advanced · Time: 20 minutes · Part of: Module 9: Data-Driven Tests and API Workflows, section 2
What You’ll Build
You’ll build a test class called DynamicTestsTest with one @TestFactory method. It generates 18 tests: three security checks for each of six endpoints, grouped per endpoint.
In your IDE, the report reads like a checklist:
1
2
3
4
5
6
7
8
9
everyEndpointIsProtected()
├─ GET /payments
│ ├─ rejects a request without a token
│ ├─ rejects a wrong token
│ └─ rejects Basic credentials
├─ POST /payments
│ ├─ rejects a request without a token
│ └─ ...
└─ ...
When you’re done, Maven reports 18 passing tests:
1
2
[INFO] Tests run: 18, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Describe the endpoints as data.
- Generate a test per endpoint and check.
What You Need
- About 20 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can write parameterized tests and use
PaymentsClient, as taught in Write Parameterized API Tests With REST Assured, send a request by method name withrequest(..), from Send Every HTTP Method in REST Assured, and you know why negative security tests matter, from Write Negative Security Tests for OAuth 2.0 in REST Assured.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
DynamicTestsTestin a newsection_02package next to the classes from the previous section, and follow every heading below. - Skip ahead: open the finished class (
DynamicTestsTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: if you haven’t cloned the examples repository yet, follow the steps in Write Parameterized API Tests With REST Assured.
Out of scope: this guide writes the list of endpoints by hand. It doesn’t cover reading it from an OpenAPI description, though the factory stays the same when you do.
Understand Dynamic Tests
The problem. A parameterized test has a fixed shape: one method, many arguments. Security checks have two dimensions, endpoints and checks, and every combination should be its own test, so one failure doesn’t hide the others. Writing a parameterized test per check repeats the endpoint list; one test with every check stops at the first failure.
The concept. A @TestFactory method doesn’t test anything itself. It returns tests, built from any data, at run time:
dynamicTest(name, executable)creates one test: a display name and a lambda.dynamicContainer(name, children)groups tests, or other containers, under a name.- The factory returns a
Stream,CollectionorIterableof these nodes.
@ParameterizedTest | @TestFactory | |
|---|---|---|
| Shape | One method, many arguments | Any tree of tests |
| Data | Annotations, fields or methods | Any code, at run time |
| Lifecycle | @BeforeEach runs per invocation | @BeforeEach runs once for the whole factory |
| Best for | A table of inputs for one check | Combinations, or tests built from external data |
When to use each. Use a parameterized test for a table of inputs to one check, as in the previous section. Use a test factory when the tests are combinations of two lists, or when the list comes from outside the test, such as an API description.
Make the endpoints data, so a new endpoint gets every check without new test code.
Meet the API Under Test
The payment lifecycle API has six operations, and its token check runs before anything else. Without Authorization: Bearer test-token, every request answers 401:
1
{"type":"about:blank","title":"Unauthorized","status":401,"detail":"A valid bearer token is required","instance":"/api/v1/payments/pay-999"}
The response also carries WWW-Authenticate: Bearer realm="payments". With the right token, the same requests get past the check, and answer for other reasons:
| Request | With the right token, and no other set-up |
|---|---|
GET /payments | 200 |
POST /payments | 400, no Idempotency-Key |
GET /payments/{id} | 200 |
PATCH /payments/{id} | 428, no If-Match |
POST /payments/{id}/authorisation | 200, or 409 once authorised |
POST /payments/{id}/execution | 202, or 409 once executing |
Your tests check these values:
- The status
401for every endpoint and every check. - The
WWW-Authenticateheader, which names the scheme the API expects.
Describe the Endpoints as Data
Set Up the Test Class
Goal: create the test class with a list of endpoints and a request without the module’s default token.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.javanibble.module_09.section_02;
import static com.javanibble.module_09.support.PaymentsClient.createPayment;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.DynamicContainer.dynamicContainer;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import com.javanibble.lifecycle.PaymentLifecycleApi;
import io.restassured.http.Method;
import io.restassured.specification.RequestSpecification;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DynamicNode;
import org.junit.jupiter.api.TestFactory;
class DynamicTestsTest {
private record Endpoint(Method method, String path) {
String label() {
return method + " " + path;
}
}
private static PaymentLifecycleApi api;
private static List<Endpoint> endpoints;
@BeforeAll
static void startApi() {
api = PaymentLifecycleApi.start();
String id = createPayment(api, "10.00");
endpoints = List.of(
new Endpoint(Method.GET, "/payments"),
new Endpoint(Method.POST, "/payments"),
new Endpoint(Method.GET, "/payments/" + id),
new Endpoint(Method.PATCH, "/payments/" + id),
new Endpoint(Method.POST, "/payments/" + id + "/authorisation"),
new Endpoint(Method.POST, "/payments/" + id + "/execution"));
}
@AfterAll
static void stopApi() {
api.close();
}
private static RequestSpecification withoutDefaults() {
return given().baseUri(api.baseUri()).port(api.port()).basePath(PaymentLifecycleApi.BASE_PATH);
}
}
What’s happening:
Endpointdescribes one operation: a method and a path.label()gives a name such asGET /payments.@BeforeAllcreates a real payment withcreatePayment(..)fromPaymentsClient, so the paths with an id point at something that exists.withoutDefaults()builds a bare request with the address and base path, but none ofPaymentsClient.spec(..)’s defaults, so no token.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Create the data the paths need, even though this API checks the token first: a made-up id here also gets
401. Many frameworks find the resource before checking access, and there a made-up id gets404, and the test proves nothing about authentication.
Generate the Tests
Generate One Container per Endpoint
Goal: give every endpoint three security checks, each its own test, grouped per endpoint.
Add this factory to the class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@TestFactory
Stream<DynamicNode> everyEndpointIsProtected() {
return endpoints.stream().map(endpoint -> dynamicContainer(endpoint.label(), Stream.of(
dynamicTest("rejects a request without a token", () ->
withoutDefaults()
.when().request(endpoint.method(), endpoint.path())
.then().statusCode(401).header("WWW-Authenticate", "Bearer realm=\"payments\"")),
dynamicTest("rejects a wrong token", () ->
withoutDefaults()
.auth().oauth2("not-the-token")
.when().request(endpoint.method(), endpoint.path())
.then().statusCode(401)),
dynamicTest("rejects Basic credentials", () ->
withoutDefaults()
.auth().preemptive().basic("admin", "admin")
.when().request(endpoint.method(), endpoint.path())
.then().statusCode(401))
)));
}
What’s happening:
- The factory maps each endpoint to a
dynamicContainer, named by its label. - Each container holds three
dynamicTests, one per check. Six endpoints and three checks make 18 tests. request(endpoint.method(), endpoint.path())sends whichever method the endpoint has.- The lambdas run later, when JUnit executes each dynamic test, not when the factory builds the tree.
Checkpoint: run DynamicTestsTest from your IDE. All 18 tests pass, in six groups named after the endpoints.
@BeforeEachand@AfterEachrun once around the whole factory, not around each dynamic test. In a check, a@BeforeEachcounter went up once per factory method, though each factory produced six or more tests. Set up what each dynamic test needs inside its lambda.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-09 -Dtest=DynamicTestsTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_09.section_02.DynamicTestsTest
[INFO] Tests run: 18, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.425 s -- in com.javanibble.module_09.section_02.DynamicTestsTest
[INFO]
[INFO] Tests run: 18, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In withoutDefaults(), replace the body with return given(PaymentsClient.spec(api));, import com.javanibble.module_09.support.PaymentsClient, and run the command again. You should see a result similar to the following:
1
2
3
4
5
6
7
8
[ERROR] Failures:
[ERROR] DynamicTestsTest.lambda$everyEndpointIsProtected$1:67 1 expectation failed.
Expected status code <401> but was <200>.
[ERROR] DynamicTestsTest.lambda$everyEndpointIsProtected$1:67 1 expectation failed.
Expected status code <401> but was <400>.
...
[ERROR] Tests run: 18, Failures: 6, Errors: 0, Skipped: 0
The shared specification carries the module’s token, so all six “without a token” tests sent one, and got through. The other twelve still pass: with their own credentials added, the API still answers 401. Look at the statuses: 200 and 202 mean the test authorised and executed the real payment, so a security test with the wrong defaults also changes data.
Maven names failures by their lambda, and its XML report names tests by index, such as everyEndpointIsProtected()[1][1]. The IDE shows GET /payments › rejects a request without a token.
Put the bare request back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
“Without a token” tests get 200 | The request starts from a specification that carries a token | Start from a bare request, like withoutDefaults() |
A test gets 404 instead of 401 | The path has an id that doesn’t exist, and the API checks it first | Create the data in @BeforeAll |
Set-up in @BeforeEach seems to run only once | @BeforeEach runs per factory, not per dynamic test | Do per-test set-up inside the lambda |
Maven reports [1][1] or lambda$.. | Surefire’s default reports don’t use display names | Read failures in the IDE, or configure Surefire’s reporter |
Try It Yourself
Exercise 1: Add a Positive Control
Add a second factory called theRightTokenIsAccepted. Generate one test per endpoint, named accepts the right token: <label>, that sends the request with auth().oauth2(PaymentLifecycleApi.TOKEN), and checks that the status isn’t 401.
Hint
The endpoints answer with different statuses for other reasons, as the table in Meet the API Under Test shows, so check not(401). You don’t need a container: map each endpoint straight to a dynamicTest. Import org.hamcrest.Matchers.not.
Solution
1
2
3
4
5
6
7
8
@TestFactory
Stream<DynamicNode> theRightTokenIsAccepted() {
return endpoints.stream().map(endpoint -> dynamicTest("accepts the right token: " + endpoint.label(), () ->
withoutDefaults()
.auth().oauth2(PaymentLifecycleApi.TOKEN)
.when().request(endpoint.method(), endpoint.path())
.then().statusCode(not(401))));
}
Add import static org.hamcrest.Matchers.not; to the class. Without this control, an API that rejects every request would pass all 18 security tests.
Exercise 2: Make the Checks Data Too
Add a factory called everyEndpointRejectsEveryCheck. Describe each check as a record with a name and a UnaryOperator<RequestSpecification> that adds its credentials, put the three checks in a list, and generate one container per endpoint with one test per check.
Hint
The “without a token” check’s operator returns the request unchanged: request -> request. Inside the container, map checks.stream() to dynamic tests, and apply the check’s operator to withoutDefaults().
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private record Check(String name, UnaryOperator<RequestSpecification> credentials) {
}
@TestFactory
Stream<DynamicNode> everyEndpointRejectsEveryCheck() {
List<Check> checks = List.of(
new Check("rejects a request without a token", request -> request),
new Check("rejects a wrong token", request -> request.auth().oauth2("not-the-token")),
new Check("rejects Basic credentials", request -> request.auth().preemptive().basic("admin", "admin")));
return endpoints.stream().map(endpoint -> dynamicContainer(endpoint.label(),
checks.stream().map(check -> dynamicTest(check.name(), () ->
check.credentials().apply(withoutDefaults())
.when().request(endpoint.method(), endpoint.path())
.then().statusCode(401)))));
}
Add import java.util.function.UnaryOperator; to the class. Now both lists are data: a new endpoint or a new check is one line.
Summary
You built DynamicTestsTest, which generates three security checks for each of six endpoints, 18 tests grouped per endpoint. A new endpoint added to the list gets every check, and can’t be forgotten.
- A
@TestFactoryreturns tests:dynamicTest(..)for each test,dynamicContainer(..)to group them. - A factory can build any tree from any data at run time, such as endpoints × checks.
@BeforeEachruns once per factory, not per dynamic test; set up per-test state inside the lambda.- Start security tests from a bare request, because a shared specification’s token turns “without a token” into “with a token”.
- Create the data the paths need, and add a positive control, so a test proves the check and not something else.
Here are the commands you used in this guide:
1
mvn test -pl module-09 -Dtest=DynamicTestsTest
What’s Next
Next: continue with Test API Workflows With REST Assured, which tests a payment from initiation to execution, first as ordered steps and then as independent tests.
The code:
- The finished test class:
DynamicTestsTest.java - The code and run commands for this module: Module 9 README
Go deeper:
- JUnit User Guide: Dynamic Tests, for factories, containers and their lifecycle.
- OWASP API Security Top 10: Broken Authentication, for why every endpoint needs these checks.
Related guides:
- Write Negative Security Tests for OAuth 2.0 in REST Assured, for the checks themselves, one endpoint at a time.
- Check Every Response Against OpenAPI With a REST Assured Filter, for the OpenAPI description an endpoint list could come from.
