Test API Workflows With REST Assured
Test a payment from initiation to execution, first as ordered steps that share one test instance, then in the preferred style of independent tests that each walk a payment to the state they test.
A payment has a lifecycle: it’s initiated, authorised, executed, and finally executed or rejected. Each step is a separate request, and each step is only allowed in the right state. The natural first idea is a test per step, run in order, each continuing where the previous one stopped. It reads like the flow, and it has a cost that shows up the first time a step fails: every step after it fails too, for reasons that have nothing to do with it. In this guide, you’ll write the workflow both ways, see the cost, and learn the style that avoids it.
Level: Advanced · Time: 25 minutes · Part of: Module 9: Data-Driven Tests and API Workflows, section 3
What You’ll Build
You’ll build a test class called PaymentWorkflowTest with two nested classes and seven tests. StepByStep walks one payment through four ordered steps that share state. IndependentTests has three tests that each create their own payment: a rejection for insufficient funds, a second authorisation, and an execution before authorisation.
The ordered steps read like the flow in the report:
1
2
3
4
5
6
7
8
9
10
PaymentWorkflowTest
├─ StepByStep
│ ├─ initiate()
│ ├─ authorise()
│ ├─ execute()
│ └─ settle()
└─ IndependentTests
├─ aLargePaymentIsRejectedForInsufficientFunds()
├─ aPaymentCanBeAuthorisedOnlyOnce()
└─ aPaymentMustBeAuthorisedBeforeExecution()
When you’re done, Maven reports seven passing tests:
1
2
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Write the workflow as ordered steps.
- Write independent tests.
What You Need
- About 25 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can use
PaymentsClient, as taught in Write Parameterized API Tests With REST Assured, and extract a value from a response, from Extract Values From a Response in REST Assured. You should know JUnit’s@Nested.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
PaymentWorkflowTestin a newsection_03package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished class (
PaymentWorkflowTest.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 uses Awaitility to wait for settlement without explaining it; Test Asynchronous APIs With REST Assured does.
Understand API Workflow Tests
The problem. A workflow is a state machine: each request moves a payment from one state to the next, and is refused in the wrong state. Testing it means getting a payment into each state first. Done as a chain of tests, each one depends on the ones before it; done carelessly as independent tests, each one repeats the whole walk.
The concept. There are two styles:
| Ordered steps | Independent tests | |
|---|---|---|
| Shape | One test per step, sharing one payment | Each test creates the payment it needs |
| JUnit features | @TestInstance(PER_CLASS), @TestMethodOrder | Small helpers, such as authorisedPayment(..) |
| When a step breaks | Every later step fails too | Each test that needs the step fails, clearly |
| Run one test alone | Not possible | Possible |
| Order and parallelism | Fixed order, no parallelism | Any order, in parallel |
When to use each. Prefer independent tests. Keep at most one ordered story, as readable documentation of the happy path, and test every rule, especially the transitions that must be refused, in independent tests.
Let each test create what it needs, so a failure points at one test.
Meet the API Under Test
The payment lifecycle API has four steps:
| Step | Request | Result |
|---|---|---|
| 1. Initiate | POST /api/v1/payments | 201, status INITIATED |
| 2. Authorise | POST /api/v1/payments/{id}/authorisation | 200, status AUTHORISED |
| 3. Execute | POST /api/v1/payments/{id}/execution | 202, status EXECUTING, with Location and Retry-After: 1 |
| 4. Settle | About half a second later, on the server | EXECUTED, or REJECTED with INSUFFICIENT_FUNDS above 5000.00 |
Each payment keeps a statusHistory, the list of states it went through. A step in the wrong state answers 409 Conflict, with a detail that names both states:
1
{"type":"about:blank","title":"Conflict","status":409,"detail":"Only an INITIATED payment can be authorised, it is AUTHORISED","instance":"/api/v1/payments/pay-9/authorisation"}
Your tests check these values:
- The status code and the
statusfield after each step. statusHistory.status, the states in order.rejectionReasonfor a rejected payment.
Write the Workflow as Ordered Steps
Set Up the Test Class
Goal: create the outer class with the API, and an order for its nested classes.
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
package com.javanibble.module_09.section_03;
import static com.javanibble.module_09.support.PaymentsClient.createPayment;
import static com.javanibble.module_09.support.PaymentsClient.newPayment;
import static com.javanibble.module_09.support.PaymentsClient.spec;
import static com.javanibble.module_09.support.PaymentsClient.validPayment;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import com.javanibble.lifecycle.PaymentLifecycleApi;
import java.time.Duration;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.ClassOrderer;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestClassOrder;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestMethodOrder;
@TestClassOrder(ClassOrderer.OrderAnnotation.class)
class PaymentWorkflowTest {
private static PaymentLifecycleApi api;
@BeforeAll
static void startApi() {
api = PaymentLifecycleApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
}
What’s happening:
- One API serves both nested classes.
@TestClassOrder(ClassOrderer.OrderAnnotation.class)runs the nested classes in the order of their@Order(..), so the story comes first in the report.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Order the Steps
Goal: walk one payment through initiation, authorisation and execution, one test per step.
Add this nested class to PaymentWorkflowTest:
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
@Nested
@Order(1)
@TestInstance(TestInstance.Lifecycle.PER_CLASS) // one instance, so fields survive between steps
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class StepByStep {
private String paymentId;
@Test
@Order(1)
void initiate() {
paymentId = newPayment(api).body(validPayment("120.00"))
.when().post("/payments")
.then().statusCode(201).body("status", equalTo("INITIATED"))
.extract().path("paymentId");
}
@Test
@Order(2)
void authorise() {
given(spec(api)).when().post("/payments/{id}/authorisation", paymentId)
.then().statusCode(200).body("status", equalTo("AUTHORISED"));
}
@Test
@Order(3)
void execute() {
given(spec(api)).when().post("/payments/{id}/execution", paymentId)
.then().statusCode(202).body("status", equalTo("EXECUTING"));
}
}
What’s happening:
@TestInstance(PER_CLASS)makes JUnit use one instance for all the methods, sopaymentId, set ininitiate(), survives into the next steps. By default, JUnit creates a new instance per test method.@TestMethodOrder(OrderAnnotation.class)with@Order(..)runs the steps in a fixed order.- Each step checks its own result: the status code and the new
status.
Checkpoint: run PaymentWorkflowTest from your IDE. Three tests run in order and pass.
Don’t forget
PER_CLASS. Without it, a check showed the field set in step 1 aspay-12, and the same field in step 2 asnull, because step 2 ran on a new instance.
Wait for Settlement
Goal: wait for the asynchronous settlement, and check the whole history.
Add this step to StepByStep:
1
2
3
4
5
6
7
8
9
10
@Test
@Order(4)
void settle() {
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
given(spec(api)).when().get("/payments/{id}", paymentId)
.then().body("status", equalTo("EXECUTED")));
given(spec(api)).when().get("/payments/{id}", paymentId)
.then().body("statusHistory.status", contains("INITIATED", "AUTHORISED", "EXECUTING", "EXECUTED"));
}
What’s happening:
- Settlement happens on the server about half a second after execution.
await().atMost(..).untilAsserted(..)repeats the check until it passes, for up to five seconds. contains(..)checks the whole history, in order, which proves the payment went through every state.
Checkpoint: run the class again. Four tests pass.
An ordered step can’t run alone. Run only
settle(), andpaymentIdisnull: it fails withIllegalArgumentException: Unnamed path parameter cannot be null (path parameter at index 0 is null). A class whose tests share state also can’t run in parallel.
Write Independent Tests
Walk Each Payment to Its State
Goal: test a rejected execution with a payment the test creates itself.
Add this nested class to PaymentWorkflowTest:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Nested
@Order(2)
class IndependentTests {
private String authorisedPayment(String amount) {
String id = createPayment(api, amount);
given(spec(api)).when().post("/payments/{id}/authorisation", id).then().statusCode(200);
return id;
}
@Test
void aLargePaymentIsRejectedForInsufficientFunds() {
String id = authorisedPayment("7500.00");
given(spec(api)).when().post("/payments/{id}/execution", id).then().statusCode(202);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
given(spec(api)).when().get("/payments/{id}", id)
.then()
.body("status", equalTo("REJECTED"))
.body("rejectionReason", equalTo("INSUFFICIENT_FUNDS")));
}
}
What’s happening:
authorisedPayment(..)creates a payment and authorises it: a short walk to the state the test needs. It checks the authorisation, so a broken step fails here with a clear message.- The test reads like a small story: an authorised payment of
7500.00, executed, is rejected for insufficient funds. - Nothing is shared with any other test, so it runs alone, in any order, or in parallel.
Checkpoint: run the class again. Five tests pass.
Test the Transitions That Must Fail
Goal: prove the API refuses steps in the wrong state.
Add these tests to IndependentTests:
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aPaymentCanBeAuthorisedOnlyOnce() {
String id = authorisedPayment("10.00");
given(spec(api)).when().post("/payments/{id}/authorisation", id).then().statusCode(409);
}
@Test
void aPaymentMustBeAuthorisedBeforeExecution() {
String id = createPayment(api, "10.00");
given(spec(api)).when().post("/payments/{id}/execution", id).then().statusCode(409);
}
What’s happening:
- Authorising twice answers
409, withOnly an INITIATED payment can be authorised, it is AUTHORISED. - Executing an initiated payment answers
409, withOnly an AUTHORISED payment can be executed, it is INITIATED. - A state machine has more wrong transitions than right ones; a suite that tests only the happy path leaves most of them untested.
Checkpoint: run the class again. All seven tests pass.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-09 -Dtest=PaymentWorkflowTest
You should see a result similar to the following, with one line per nested class:
1
2
3
4
5
6
7
8
9
[INFO] Running com.javanibble.module_09.section_03.PaymentWorkflowTest
[INFO] Running com.javanibble.module_09.section_03.PaymentWorkflowTest$StepByStep
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.942 s -- in com.javanibble.module_09.section_03.PaymentWorkflowTest$StepByStep
[INFO] Running com.javanibble.module_09.section_03.PaymentWorkflowTest$IndependentTests
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.617 s -- in com.javanibble.module_09.section_03.PaymentWorkflowTest$IndependentTests
[INFO]
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In StepByStep.authorise(), change the path to the American spelling, /payments/{id}/authorization, and run the command again. You should see a result similar to the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
[ERROR] Failures:
[ERROR] PaymentWorkflowTest.authorise 1 expectation failed.
Expected status code <200> but was <404>.
[ERROR] PaymentWorkflowTest.execute 1 expectation failed.
Expected status code <202> but was <409>.
[ERROR] Errors:
[ERROR] PaymentWorkflowTest.settle » ConditionTimeout Assertion condition defined as a Lambda expression in com.javanibble.module_09.section_03.PaymentWorkflowTest$StepByStep 1 expectation failed.
JSON path status doesn't match.
Expected: EXECUTED
Actual: INITIATED
within 5 seconds.
One wrong path made three tests fail. Only authorise points at the cause; execute fails with a 409 and settle with a five-second timeout, though nothing is wrong with either. That’s the cost of ordered steps. The independent tests still pass, because they use their own helper with the right path.
Put the path back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Unnamed path parameter cannot be null in a step | The step ran alone, or without PER_CLASS | Run the whole class, or rewrite the step as an independent test |
| Several steps fail after one change | An earlier step failed, and the later ones depend on it | Fix the first failing step; prefer independent tests |
409 with Only an AUTHORISED payment can be executed | The payment isn’t in the state the step expects | Walk it there first, with a helper such as authorisedPayment(..) |
ConditionTimeout ... within 5 seconds | Settlement didn’t reach the expected state | Check the amount: above 5000.00 is REJECTED |
Try It Yourself
Exercise 1: Refuse a Second Execution
Add a test to IndependentTests called aPaymentCanBeExecutedOnlyOnce. Execute an authorised payment, execute it again straight away, and check that the second request answers 409 with the detail Only an AUTHORISED payment can be executed, it is EXECUTING.
Hint
Start from authorisedPayment("10.00"). The first execution answers 202; the payment is EXECUTING until settlement, half a second later.
Solution
1
2
3
4
5
6
7
8
9
10
@Test
void aPaymentCanBeExecutedOnlyOnce() {
String id = authorisedPayment("10.00");
given(spec(api)).when().post("/payments/{id}/execution", id).then().statusCode(202);
given(spec(api)).when().post("/payments/{id}/execution", id)
.then()
.statusCode(409)
.body("detail", equalTo("Only an AUTHORISED payment can be executed, it is EXECUTING"));
}
Exercise 2: Check the History of a Rejected Payment
Add a test to IndependentTests called aRejectedPaymentHasTheWholeHistory. Execute an authorised payment of 7500.00, wait until it’s REJECTED, and check that statusHistory.status is INITIATED, AUTHORISED, EXECUTING, REJECTED, in that order.
Hint
Wait with await().atMost(..).untilAsserted(..) on the status, then check the history with contains(..) in a second request, as settle() does.
Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void aRejectedPaymentHasTheWholeHistory() {
String id = authorisedPayment("7500.00");
given(spec(api)).when().post("/payments/{id}/execution", id).then().statusCode(202);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
given(spec(api)).when().get("/payments/{id}", id).then().body("status", equalTo("REJECTED")));
given(spec(api)).when().get("/payments/{id}", id)
.then().body("statusHistory.status", contains("INITIATED", "AUTHORISED", "EXECUTING", "REJECTED"));
}
The limit is strict: an authorised payment of exactly 5000.00 settles as EXECUTED.
Summary
You built PaymentWorkflowTest, which walks one payment through four ordered steps, and tests a rejection and two refused transitions with independent tests. You saw one broken step fail three ordered tests, while the independent ones kept pointing at the truth.
- Ordered steps need
@TestInstance(PER_CLASS)to share a field, and@TestMethodOrderwith@Order(..)to run in sequence. - They read like the flow, but a failed step fails every later step, no step runs alone, and the class can’t run in parallel.
- Independent tests create their own payment and walk it to the state they need with small helpers.
- Test the transitions that must be refused, such as a second authorisation, and the outcomes other than success.
- Wait for asynchronous steps with Awaitility, never a fixed sleep.
Here are the commands you used in this guide:
1
mvn test -pl module-09 -Dtest=PaymentWorkflowTest
What’s Next
Next: continue with Test Idempotency, ETags and Pagination in REST Assured, which tests idempotent replay, conditional reads and writes with ETag, and following Link headers through every page.
The code:
- The finished test class:
PaymentWorkflowTest.java - The code and run commands for this module: Module 9 README
Go deeper:
- JUnit User Guide: Test Instance Lifecycle, for
PER_CLASSand why it isn’t the default. - JUnit User Guide: Test Execution Order, for ordering methods and classes.
- Awaitility, for waiting on asynchronous results.
Related guides:
- Run REST Assured Tests in Parallel With JUnit, for why independent tests matter when the suite runs in parallel.
- Generate Dynamic API Tests With REST Assured, for creating the data a test needs before it runs.
