Engineering a Reliable REST API Integration Test Suite
An approach and set of best practices for REST API integration testing with REST Assured: what the suite must prove, how to break an API down into test cases, how to structure the framework, and how to run it in CI.
A passing integration suite is evidence that the deployed API, wired to its real database, security layer and configuration, keeps its published contract over real HTTP. This reference sets out the approach and best practices for building that suite with REST Assured: what it must prove, how to break an API down into test cases, how to structure the framework, and how to run it in a pipeline.
Level: Intermediate to advanced · Stack: REST Assured 5, JUnit Jupiter, Java 17 · Companion to: the REST Assured Learning Guide
What Integration Tests Must Prove
“It returned 200” is not evidence of anything. When the suite is green, these seven statements must be true:
- The contract holds. Every response matches the OpenAPI spec: status codes, headers, body schema, formats and error shape. Nothing undocumented leaks out.
- The behaviour is correct. Each documented use case produces the right result, and each business rule is enforced, both when it should allow and when it should refuse.
- Bad input is rejected safely. Invalid, malformed, missing or hostile input gets a clear
4xxwith a useful error body. It never causes a5xx, a hang or a partial write. - Access is enforced. Unauthenticated callers are refused. Authenticated callers can only do what their permissions allow, and only to resources they own.
- State is correct and consistent. What the API says it did is what actually happened: read-back shows the change, and a rejected request changes nothing.
- It is safe to retry and to call concurrently. Retries do not duplicate effects. Parallel requests do not corrupt data or break invariants.
- The wiring works. Configuration, serialisation, database mappings, transactions, filters, interceptors and outbound calls work together, which unit tests with mocks cannot show.
If a test does not help prove one of these statements, question why it exists.
Scope
API integration tests treat the service as a black box behind HTTP. They sit between fast, isolated unit tests and slow, broad end-to-end journeys, and they catch the defects that live in the wiring between components.
| Level | What is real | What is replaced | Proves | Speed |
|---|---|---|---|---|
| Unit | One class or function | Everything else (mocks) | Logic is correct in isolation | Milliseconds |
| Component (service in isolation) | The whole service, its database (Testcontainers) | External services (WireMock stubs) | The service works as a unit over HTTP; failure handling | Seconds |
| Contract | The interface agreement | Both sides’ internals | Consumer and provider agree (Pact, OpenAPI checks) | Seconds |
| API integration (this guide) | The deployed service and its real neighbours in a shared environment | Only true third parties (sandboxes) | The contract and behaviour hold in a real environment | Minutes |
| End-to-end | Several services, sometimes a UI | Nothing | A user journey works across systems | Tens of minutes |
Design one REST Assured suite that runs at both the component level and the deployed level. Configuration switches the base URL, the identity provider and the data setup; the tests themselves do not change.
In scope
- Every public operation in the API specification, plus documented error behaviour
- Authentication and authorization at the API boundary
- Effects you can observe through the API (read-back) or a test-only endpoint
- Multi-step workflows within this one API (create, read, update, delete, state changes)
Out of scope (covered elsewhere)
- Internal logic branches with no visible HTTP effect: unit tests
- Load, stress and soak testing: performance tests (Gatling, k6, JMeter)
- Penetration testing and fuzzing at scale: security testing
- UI behaviour and cross-system journeys: end-to-end tests
- Testing the identity provider itself: the suite uses tokens from it, but testing the token endpoint belongs to the identity provider’s own tests
Principles
These twelve rules decide whether the suite stays a trusted safety net or turns into noise that people rerun until it passes.
What to Test
- Test the contract, not the implementation. Derive expectations from the API spec and the requirements. A test written by reading the code checks that the code does what it does.
- Let risk set the depth. Go deepest where a failure costs most: writes, money, personal data, permissions, irreversible actions. A read-only lookup endpoint needs less.
- Expect more failure cases than success cases. Each operation has one or two ways to succeed and many ways to fail. Most production incidents and security holes are in the failure paths.
- Assert outcomes, not just status codes. Check the status, headers, body and resulting state together. Read back after every write; check that nothing changed after every rejected write.
How Tests Behave
- Every test is independent. No test depends on another test’s data or run order. Each test arranges what it needs, so the suite runs in parallel and in any order.
- Deterministic or quarantined. No
Thread.sleep, no reliance on the current time, no shared mutable records. Poll with a timeout for asynchronous results. A flaky test is a bug: fix it or quarantine it within days. - Fast feedback beats complete feedback. A 3-minute smoke run after each deployment is worth more than a 2-hour suite that runs once a week. Tag tests so each stage runs what it needs.
- Leave the environment as you found it. Clean up what you create, or use clearly marked disposable data that a job purges.
How Tests Are Written
- Tests read like specifications. The class and method names state the rule; the body follows given / when / then. A reviewer should understand the rule without opening framework code.
- Separate what from how. Tests say what they expect; clients, builders and assertion helpers handle HTTP details. A changed URL or header is fixed in one place.
- Treat test code as production code. Code review, static analysis, no copy-paste, no commented-out tests, clear ownership.
- No secrets or environment details in code. URLs, credentials and keys come from configuration and a secret store, never from the repository.
Systematic Decomposition
Break the API down top-down through five levels: API → resource → operation → behaviour → test case. Each level produces an artifact you can review, and the last one is the coverage matrix. The worked example throughout is a generic Orders API.
- Inventory the surface. From the OpenAPI spec, list every operation:
POST /orders,GET /orders/{id},GET /orders,PATCH /orders/{id},DELETE /orders/{id},POST /orders/{id}/cancel. For each, note the caller types, the auth scheme and the permissions required. - Rate the risk. Score each operation High / Medium / Low on impact (data loss, money, privacy, irreversibility) and change frequency. Risk decides how many dimensions you cover in depth.
- Model the resource lifecycle. Draw the states and transitions:
DRAFT → PLACED → SHIPPED → DELIVERED, withCANCELLEDreachable only fromDRAFTorPLACED. List the allowed transitions and, just as important, the forbidden ones. - Extract the rules. Write each rule as one testable sentence: “quantity is between 1 and 100”, “an order needs at least one line”, “a shipped order cannot be cancelled”, “customers see only their own orders”. Each rule needs at least one passing and one failing test.
- Apply the test dimensions. Run each operation through the test dimensions catalogue. Each dimension that applies becomes a group of cases; one that doesn’t apply gets a stated reason.
- Design the cases with techniques. Use the test design techniques (partitions, boundaries, decision tables, state tables, permission matrix), so coverage comes from method, not memory.
- Prioritise and tag. Mark each case
smoke,regression,securityorslow. Smoke = one non-destructive happy path per critical operation.
The Orders lifecycle from step 3 looks like this:
stateDiagram-v2
direction LR
[*] --> DRAFT
DRAFT --> PLACED
PLACED --> SHIPPED
SHIPPED --> DELIVERED
DRAFT --> CANCELLED
PLACED --> CANCELLED
DELIVERED --> [*]
CANCELLED --> [*]
Worked Example: POST /orders
| Dimension | Example cases |
|---|---|
| Happy path | Valid order returns 201, Location header, schema-valid body with status PLACED; GET on the Location returns the same order |
| Validation | Missing lines; empty lines; quantity 0, 1, 100, 101; unknown product ID; wrong type ("quantity": "two"); malformed JSON; unknown extra field |
| Business rules | Product out of stock; customer account suspended; order total above the allowed maximum |
| Authentication | No token; expired token; token with an invalid signature; token for another API (wrong audience) |
| Authorization | Missing orders:write permission; ordering on behalf of another customer; client sets server-owned fields (status, customerId, total) |
| Idempotency | Same Idempotency-Key and body gives one order; same key with a different body is rejected |
| Concurrency | Two orders for the last item in stock in parallel: exactly one succeeds |
| HTTP semantics | Content-Type: text/plain gives 415; Accept: application/xml gives 406; PUT /orders gives 405 |
| Side effects | Stock reduced by the ordered quantity; OrderPlaced event published; nothing changes when the request is rejected |
Worked Example: the Full Lifecycle (CRUD Workflow)
One test per resource chains the operations to prove they agree with each other:
POST /orders→201, captureidGET /orders/{id}→200, body equals what was sentPATCH /orders/{id}→200;GETagain shows the change persisted, unchanged fields untouchedDELETE /orders/{id}→204GET /orders/{id}→404; a secondDELETE→404(or204, if documented as idempotent)
Keep this as one workflow test. Every other test should arrange its own state directly rather than chaining many steps, so a failure points to one cause.
Test Dimensions
Check every operation against these 15 dimensions. Not all apply everywhere, but each skipped one should have a reason you could defend in review.
| # | Dimension | What to test | Expected |
|---|---|---|---|
| 1 | Contract / schema | Body validates against the JSON schema from the spec; required fields present; types and formats (ISO 8601 dates, UUIDs, enums) correct; no undocumented or internal fields | Schema passes |
| 2 | Happy path | Every documented success case, with optional fields both present and absent | 200 / 201 / 204 and correct body |
| 3 | Input validation | Missing, null, empty, wrong type, too short or long, out of range, invalid enum, malformed JSON, unknown fields, unicode, leading/trailing spaces | 400 with field-level detail, never 5xx |
| 4 | Path and query parameters | Unknown ID; malformed ID (abc where a UUID is expected); very long values; encoded and special characters (%2F, ../); invalid or repeated query params | 400 or 404, never 5xx |
| 5 | Business rules | Each rule passing and failing; combinations of rules | 422 (or the documented code) with a specific error code |
| 6 | Authentication | No credentials; malformed, expired, not-yet-valid, wrongly signed or revoked token; wrong issuer or audience | 401 with WWW-Authenticate, no data |
| 7 | Authorization | Missing permission or role; another user’s resource (object-level access, BOLA/IDOR); user calling an admin operation (function-level); setting fields the client must not control (mass assignment) | 403, or 404 to hide existence, applied consistently |
| 8 | Resource state | Allowed and forbidden transitions; operating on deleted or final-state resources | 409 for a wrong state |
| 9 | Idempotency and retries | GET, PUT, DELETE repeated safely; POST with an idempotency key, replayed with the same and with a different body | One effect only |
| 10 | Concurrency | Parallel updates to one resource; double submit; optimistic locking with ETag / If-Match | No lost updates; 409 / 412 for the loser |
| 11 | HTTP semantics and headers | 405 for wrong method; 415 wrong Content-Type; 406 unsupported Accept; Location on create; caching headers; CORS; correlation ID echoed; security headers | Correct codes and headers |
| 12 | Collections | Pagination (first, middle, last, past the end, size 0, max size); sorting; filtering; empty results; stable ordering | Correct items and paging metadata |
| 13 | Error format | All errors follow one format (e.g. RFC 9457 Problem Details); no stack traces, SQL, class names or host names | Consistent, safe error body |
| 14 | Side effects and consistency | Read-back after write; related resources updated; events or messages published; nothing changed after a rejected request | State matches the operation |
| 15 | Resilience (component level) | Dependency slow, down or returning errors (via WireMock); timeouts; retries; circuit breaker | 502 / 503 / 504 with a clean error, no hang |
Status codes. Assert the exact, semantically correct code, not a range. A
200where201is documented, or a500caused by client input, is a defect even if the client “works”.
Non-functional smoke. Add a generous response-time ceiling on key operations (e.g.
time(lessThan(2000L))) to catch gross regressions. It is a tripwire, not a performance test.
Test Design Techniques
Five classic techniques turn a rule or a field into a small, complete set of cases. Use them instead of guessing at edge cases.
Equivalence Partitioning
Split each input into groups the API should treat the same way, and test one value from each. For quantity (1–100): one valid value (50), one too low (-5), one too high (500), one of the wrong type ("two"), and null.
Boundary Value Analysis
Defects cluster at the edges. Test each edge and its neighbours: 0, 1, 2 and 99, 100, 101. The same applies to string lengths, list sizes, dates and page sizes.
Decision Tables
When several conditions combine, list every combination and its expected outcome, and turn each row into a parameterised test case.
| In stock | Account active | Total within limit | Expected |
|---|---|---|---|
| Yes | Yes | Yes | 201 |
| No | Yes | Yes | 422 OUT_OF_STOCK |
| Yes | No | Yes | 422 ACCOUNT_SUSPENDED |
| Yes | Yes | No | 422 LIMIT_EXCEEDED |
| No | No | No | 422 with the documented precedence (which error wins) |
State-Transition Testing
From the lifecycle model, test each allowed transition once and each forbidden transition once. For cancel: allowed from DRAFT and PLACED; forbidden from SHIPPED, DELIVERED and CANCELLED (409).
Permission Matrix
List personas against operations and mark the expected outcome. Always include two users with the same role, so you can prove one cannot touch the other’s data.
| Operation | Anonymous | Customer (own order) | Customer (other’s order) | Support agent | Admin |
|---|---|---|---|---|---|
GET /orders/{id} | 401 | 200 | 404 | 200 | 200 |
PATCH /orders/{id} | 401 | 200 | 404 | 403 | 200 |
DELETE /orders/{id} | 401 | 403 | 404 | 403 | 204 |
Turn each row and cell into a parameterised test (
@MethodSourceor@CsvSource), so the matrix in the doc and the matrix in the code stay the same thing.
Framework Architecture
The framework has three layers above REST Assured, and each changes for exactly one reason. Tests state expectations; domain helpers know how to call the API and check its answers; infrastructure knows where the API is and who is calling.
flowchart TB
T["<b>Tests</b><br/>scenarios · expected outcomes · tags"]
D["<b>Domain helpers</b><br/>clients · builders · assertions · fixtures"]
I["<b>Infrastructure</b><br/>config · specs · auth · logging · reporting"]
R["<b>REST Assured</b>"]
A[("API under test")]
T --> D --> I --> R -->|HTTP| A
A changed URL, header or auth scheme is fixed in one helper or infrastructure class, and no test changes.
| Layer | Owns | Must not contain | Changes when |
|---|---|---|---|
| Tests | Scenarios, expected outcomes, tags | URLs, tokens, raw JSON strings, HTTP config | A requirement changes |
| Domain helpers | Endpoint paths, request building, reusable assertions, fixtures | Expectations about a specific scenario | The API’s shape changes |
| Infrastructure | Base URI, timeouts, auth, logging, reporting | Anything about a specific resource | The environment or auth setup changes |
Tool choices
| Concern | Tool |
|---|---|
| HTTP | REST Assured |
| Lifecycle, tags, parameterisation, parallelism | JUnit Jupiter |
| Rich object assertions | AssertJ |
| (De)serialisation | Jackson |
| Contract checks | json-schema-validator |
| Async polling | Awaitility |
| Component level | Testcontainers and WireMock |
| Reports | Allure |
Project Structure
Keep API tests in their own Maven module (or repository) so they can run against any environment without building the service. Organise tests by business capability, never by HTTP method or by tester.
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
api-integration-tests/
├── pom.xml # rest-assured, json-schema-validator, junit-jupiter,
│ # assertj, jackson, awaitility, allure, testcontainers, wiremock
└── src/test/
├── java/com/example/api/
│ ├── framework/ # reusable; no assertions about the product
│ │ ├── config/
│ │ │ ├── TestConfig.java # reads env-specific settings, fails fast if missing
│ │ │ └── Environment.java # LOCAL, DEV, TEST, STAGING
│ │ ├── http/
│ │ │ ├── Specs.java # base Request/ResponseSpecifications
│ │ │ └── MaskingLogFilter.java # logs on failure, masks secrets
│ │ ├── auth/
│ │ │ ├── Persona.java # CUSTOMER_A, CUSTOMER_B, SUPPORT, ADMIN, NO_PERMISSIONS
│ │ │ ├── TokenProvider.java # gets and caches tokens per persona
│ │ │ └── BadTokens.java # expired, tampered, wrong-audience tokens
│ │ ├── client/ # one client per resource; returns Response
│ │ │ ├── OrdersClient.java
│ │ │ └── ProductsClient.java
│ │ ├── model/ # request/response records (ideally generated from OpenAPI)
│ │ ├── data/
│ │ │ ├── OrderRequests.java # builders with valid defaults
│ │ │ └── Fixtures.java # creates prerequisite data via API or seed endpoints
│ │ ├── assertions/
│ │ │ └── Problems.java # reusable error-response specs
│ │ └── junit/
│ │ ├── CleanupExtension.java # deletes what a test created
│ │ └── TestNameHeaderExtension.java # sends test name as a header for log tracing
│ └── tests/
│ ├── BaseApiIT.java
│ ├── orders/
│ │ ├── CreateOrderIT.java
│ │ ├── CreateOrderValidationIT.java
│ │ ├── OrderAccessControlIT.java
│ │ ├── OrderLifecycleIT.java
│ │ ├── OrderIdempotencyIT.java
│ │ └── SearchOrdersIT.java
│ ├── products/
│ └── crosscutting/ # rules every endpoint must follow
│ ├── AuthenticationIT.java # parameterised over all endpoints
│ ├── HttpSemanticsIT.java
│ ├── SecurityHeadersIT.java
│ └── ErrorFormatIT.java
└── resources/
├── config/{local,dev,test,staging}.properties # URLs and flags only, no secrets
├── schemas/ # JSON schemas per response type
├── testdata/ # CSV / JSON for parameterised tests
├── junit-platform.properties # parallel execution
└── logback-test.xml
Conventions
- Name test classes
*IT.javaand run them with maven-failsafe-plugin (mvn verify); surefire stays for unit tests. - One class per operation and concern (
CreateOrderValidationIT), so a red class name already tells you what broke. - Method names state the rule (
rejectsOrderWhenQuantityExceedsMaximum), with@DisplayNamefor readable reports. crosscutting/tests take a list of all endpoints, so a new endpoint inherits authentication, header and error-format checks by adding one line.- Select the environment with
-Denv=test; nothing environment-specific in test code. - Generate
model/classes and schemas from the OpenAPI spec where possible, so contract drift breaks the build.
REST Assured Patterns
The examples below are patterns to adapt, not a drop-in library. They target REST Assured 5, JUnit Jupiter and Java 17.
Specifications Built per Call, Never Global Statics
RestAssured.baseURI, RestAssured.filters and similar static fields are shared across threads, so parallel tests leak settings into each other. Build specifications instead.
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
public final class Specs {
private static final RestAssuredConfig CONFIG = RestAssuredConfig.config()
.httpClient(HttpClientConfig.httpClientConfig()
.setParam("http.connection.timeout", 5_000)
.setParam("http.socket.timeout", 15_000));
public static RequestSpecification anonymous() {
return new RequestSpecBuilder()
.setBaseUri(TestConfig.baseUri())
.setConfig(CONFIG)
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.addHeader("X-Correlation-ID", UUID.randomUUID().toString())
.addFilter(new MaskingLogFilter())
.addFilter(new AllureRestAssured())
.build();
}
public static RequestSpecification as(Persona persona) {
return new RequestSpecBuilder()
.addRequestSpecification(anonymous())
.addHeader("Authorization", "Bearer " + TokenProvider.tokenFor(persona))
.build();
}
}
Building the spec per persona, rather than baking one token into a shared spec, is what makes access-control tests possible.
Resource Clients: HTTP Details in One Place
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class OrdersClient {
private final RequestSpecification spec;
public OrdersClient(RequestSpecification spec) { this.spec = spec; }
public Response create(Object body) {
return given(spec).body(body).when().post("/v1/orders");
}
public Response get(String id) {
return given(spec).pathParam("id", id).when().get("/v1/orders/{id}");
}
public Response search(Map<String, ?> query) {
return given(spec).queryParams(query).when().get("/v1/orders");
}
}
Clients return Response and make no assertions: each test decides what it expects. create accepts Object so negative tests can send a Map or raw string, because a typed record cannot express a missing required field or a wrong type.
Builders with Valid Defaults
1
2
3
4
5
6
7
var order = OrderRequests.valid() // every field valid by default
.withLine(product.id(), 3)
.build();
var missingLines = OrderRequests.valid()
.asMap() // Map<String,Object> for malformed cases
.without("lines");
Each test states only the field it is about, which keeps the rule visible.
Happy Path: Status, Headers, Schema, Body and Read-Back
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
class CreateOrderIT extends BaseApiIT {
private final OrdersClient orders = new OrdersClient(Specs.as(CUSTOMER_A));
@Test
@Tag("smoke")
@DisplayName("A valid order is created, returned and readable at its Location")
void createsOrder() {
var product = fixtures.productInStock(10);
var location = orders.create(OrderRequests.valid().withLine(product.id(), 3).build())
.then()
.statusCode(201)
.header("Location", matchesPattern(".*/v1/orders/[0-9a-f-]{36}$"))
.body(matchesJsonSchemaInClasspath("schemas/order.json"))
.body("status", equalTo("PLACED"))
.body("lines[0].quantity", equalTo(3))
.extract().header("Location");
given(Specs.as(CUSTOMER_A)).get(location)
.then().statusCode(200).body("lines", hasSize(1));
fixtures.assertStock(product.id(), 7); // side effect
}
}
Parameterised Validation with a Reusable Error Spec
1
2
3
4
5
6
7
8
@ParameterizedTest(name = "quantity {0} is rejected")
@ValueSource(ints = {-1, 0, 101, 1000})
void rejectsQuantityOutsideRange(int quantity) {
orders.create(OrderRequests.valid().withLine(product.id(), quantity).build())
.then()
.statusCode(400)
.spec(Problems.validationError("lines[0].quantity"));
}
Problems.validationError(field) is a ResponseSpecification that checks the content type application/problem+json, the standard fields, the field reference, and that no stack trace is present. Every negative test reuses it, which keeps the error format consistent across the API.
Access Control: Two Users, Same Role
1
2
3
4
5
6
7
@Test
void customerCannotReadAnotherCustomersOrder() {
var orderOfA = fixtures.orderFor(CUSTOMER_A);
new OrdersClient(Specs.as(CUSTOMER_B)).get(orderOfA.id())
.then().statusCode(404); // or 403, per the documented policy
}
Concurrency
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void lastItemInStockIsSoldOnlyOnce() {
var product = fixtures.productInStock(1);
var codes = IntStream.range(0, 2)
.mapToObj(i -> CompletableFuture.supplyAsync(() ->
orders.create(OrderRequests.valid().withLine(product.id(), 1).build()).statusCode()))
.toList().stream()
.map(CompletableFuture::join)
.toList();
assertThat(codes).containsExactlyInAnyOrder(201, 422);
fixtures.assertStock(product.id(), 0);
}
Asynchronous Results: Poll, Never Sleep
1
2
await().atMost(Duration.ofSeconds(20)).pollInterval(Duration.ofMillis(500))
.untilAsserted(() -> orders.get(id).then().body("status", equalTo("SHIPPED")));
Never use
Thread.sleepto wait for an asynchronous result. A fixed sleep is either too short (flaky) or too long (slow); polling with a timeout is neither.
Assertion Style
- Use REST Assured’s
then()with Hamcrest for the HTTP-level checks (status, headers, schema, simple paths). - Extract to a record and use AssertJ for complex comparisons (
usingRecursiveComparison().ignoringFields("id", "createdAt")). - Never compare whole response strings; field order and formatting are not part of the contract.
- Parse decimals as
BigDecimal(JsonPathConfig.NumberReturnType.BIG_DECIMAL) whenever exact values matter;floatanddoublelose precision.
Test Data and Environments
Most flaky API suites are flaky because of data, not code. Settle the data strategy before the suite grows.
Data Rules
- Each test creates what it needs. Arrange data through the API itself, a test-only seed endpoint, or database fixtures at the component level. Shared long-lived records get modified by other tests and break unpredictably.
- Make data unique by construction. Prefix every created value with a run ID (
it-<runId>-<uuid>), so parallel runs never collide and leftovers are easy to find and purge. - Arrange directly, act once. Set up the state the test needs in the quickest reliable way, then make the one call under test. Don’t chain ten API calls to reach a state unless the chain is what you’re testing.
- Document fixed fixtures. Some data cannot be created on demand (a third-party sandbox account, a special configuration). Keep these in one
Fixturesclass that says what each is for. - Clean up. A JUnit extension deletes what the test registered, and a scheduled job purges anything with the test prefix that was left behind.
- Synthetic data only. Never copy production data into test environments.
Environments
| Environment | Purpose | Suite | Dependencies | Destructive tests |
|---|---|---|---|---|
| Local / CI component | Fast feedback per commit | Full, incl. resilience | Testcontainers for the database and broker; WireMock for external services | Yes |
| DEV / TEST | Real integration with neighbouring services | Full regression | Real services; sandboxes for third parties | Yes |
| STAGING | Release gate with production-like config | Smoke + critical regression | Production-like | Limited, with cleanup |
| PRODUCTION | Post-deployment check | Read-only smoke with a dedicated synthetic account | Real | Never |
Configuration and Secrets
- One properties file per environment holds URLs and feature flags;
TestConfigfails fast at startup if a value is missing. - Client secrets and keys come from environment variables or the CI secret store, never from the repository or logs.
- Use dedicated test OAuth clients and users per environment with the minimum permissions needed.
- Define a fixed set of personas (
ANONYMOUS,CUSTOMER_A,CUSTOMER_B,SUPPORT,ADMIN,NO_PERMISSIONS) and cache one token per persona per run.
Never commit secrets, tokens or client keys to the test repository, and make sure the logging filter masks them in every report.
Execution: Tagging, Parallelism, CI and Reporting
Tags let one suite serve every pipeline stage; parallelism keeps it fast; reporting makes failures quick to diagnose.
Tags
| Tag | Meaning | Runs | Time budget |
|---|---|---|---|
smoke | One non-destructive happy path per critical operation | After every deployment, incl. production (read-only subset) | < 3 min |
regression | Full functional and negative coverage | Every merge to main | < 15 min |
security | Authentication, authorization, headers | Every merge and before every release | < 10 min |
resilience | Fault injection with WireMock | Component stage only | < 10 min |
slow | Long-running async flows | Nightly | No limit |
quarantine | Known flaky, under investigation, excluded from gates | Nightly, reported separately | Fix within a week |
1
2
mvn verify -Denv=test -Dgroups="smoke"
mvn verify -Denv=test -Dgroups="regression | security" -DexcludedGroups="quarantine"
Parallel Execution
1
2
3
4
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.default=concurrent
junit.jupiter.execution.parallel.config.strategy=fixed
junit.jupiter.execution.parallel.config.fixed.parallelism=8
Parallel runs only work when tests are independent and data is unique (principles 5 and 6). Mark the rare test that changes global state with
@ResourceLockor@Isolated.
Pipeline Order
flowchart LR
B["Build +<br/>unit tests"] --> C["Component tests<br/>incl. resilience"]
C --> K["Contract<br/>checks"]
K --> T["TEST<br/>smoke → regression + security"]
T --> S["STAGING<br/>smoke + critical regression"]
S --> P["PRODUCTION<br/>read-only smoke"]
- Build and unit tests (surefire).
- Component tests: service started with Testcontainers and WireMock; full suite incl.
resilience. - Contract checks: OpenAPI validation and consumer pacts.
- Deploy to TEST:
smokefirst (stop if red), thenregressionandsecurity. - Deploy to STAGING:
smokeplus critical regression as the release gate. - Deploy to PRODUCTION: read-only
smoke; roll back if red.
Reporting and Diagnosis
- Attach the full request and response to every failure (Allure with
AllureRestAssured), with secrets masked. - Send a correlation ID and the test name as headers, so a failure links straight to the service’s logs and traces.
- Link each test to the requirement or rule it covers (
@Link,@Issue, or a custom annotation) for traceability. - Track pass rate, flaky rate and suite duration over time. A rising flaky rate is the earliest sign the suite is losing trust.
Handling Flaky Tests
- Rerun once in CI only to detect flakiness, never to hide it; record every pass-on-retry.
- Quarantine with a ticket and an owner.
- Fix the root cause, which is usually shared data, timing (a missing poll) or order dependence.
- Return the test to the gate, or delete it if it adds no value.
Coverage Matrix and Review Checklist
The coverage matrix is the end product of the decomposition: one row per operation, one column per dimension from Test Dimensions. Mark each cell Y (covered), N (gap) or – (not applicable, with a reason).
An N on a High-risk operation blocks the release.
| Operation | Risk | Contract | Happy | Validation | Params | Rules | AuthN | AuthZ | State | Idempotency | Concurrency | HTTP | Collections | Errors | Side effects | Resilience |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
POST /orders | High | – | – | |||||||||||||
GET /orders/{id} | Medium | – | – | – | – | – | ||||||||||
GET /orders | Medium | – | – | – | – | |||||||||||
PATCH /orders/{id} | High | – | ||||||||||||||
DELETE /orders/{id} | High | – | – | |||||||||||||
POST /orders/{id}/cancel | High | – | – |
Review Checklist for Every New or Changed Operation
- Happy path checks status, headers, schema, body values and read-back
- Every required field tested missing, null, empty and with the wrong type
- Boundaries tested for each numeric, length, size and date constraint
- Path and query parameters tested with unknown, malformed and encoded values
- Every business rule has a passing and a failing test with its specific error code
- No credentials, an expired token and a tampered token each return
401 - Missing permission returns
403; another user’s resource is refused - Client cannot set server-owned fields
- Forbidden state transitions return
409 - Retries and parallel calls are proven safe for every write
- Errors follow the standard format and leak no internals
- Side effects verified; rejected requests change nothing
- Test creates and cleans up its own data; runs in parallel and in any order
- No
Thread.sleep, hard-coded URLs, tokens or secrets - Tagged and linked to the requirement it covers
- Coverage matrix row updated
Where to Start
Build
TestConfig,Specs,TokenProviderand one client, then cover one important operation across every dimension before adding breadth. That first operation becomes the template the rest of the suite copies.
