Post

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.

Engineering a Reliable REST API Integration Test Suite

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:

  1. The contract holds. Every response matches the OpenAPI spec: status codes, headers, body schema, formats and error shape. Nothing undocumented leaks out.
  2. 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.
  3. Bad input is rejected safely. Invalid, malformed, missing or hostile input gets a clear 4xx with a useful error body. It never causes a 5xx, a hang or a partial write.
  4. Access is enforced. Unauthenticated callers are refused. Authenticated callers can only do what their permissions allow, and only to resources they own.
  5. 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.
  6. It is safe to retry and to call concurrently. Retries do not duplicate effects. Parallel requests do not corrupt data or break invariants.
  7. 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.

LevelWhat is realWhat is replacedProvesSpeed
UnitOne class or functionEverything else (mocks)Logic is correct in isolationMilliseconds
Component (service in isolation)The whole service, its database (Testcontainers)External services (WireMock stubs)The service works as a unit over HTTP; failure handlingSeconds
ContractThe interface agreementBoth sides’ internalsConsumer and provider agree (Pact, OpenAPI checks)Seconds
API integration (this guide)The deployed service and its real neighbours in a shared environmentOnly true third parties (sandboxes)The contract and behaviour hold in a real environmentMinutes
End-to-endSeveral services, sometimes a UINothingA user journey works across systemsTens 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

  1. 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.
  2. 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.
  3. 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.
  4. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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

  1. 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.
  2. 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.
  3. Treat test code as production code. Code review, static analysis, no copy-paste, no commented-out tests, clear ownership.
  4. 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.

  1. 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.
  2. 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.
  3. Model the resource lifecycle. Draw the states and transitions: DRAFT → PLACED → SHIPPED → DELIVERED, with CANCELLED reachable only from DRAFT or PLACED. List the allowed transitions and, just as important, the forbidden ones.
  4. 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.
  5. 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.
  6. 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.
  7. Prioritise and tag. Mark each case smoke, regression, security or slow. 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

DimensionExample cases
Happy pathValid order returns 201, Location header, schema-valid body with status PLACED; GET on the Location returns the same order
ValidationMissing lines; empty lines; quantity 0, 1, 100, 101; unknown product ID; wrong type ("quantity": "two"); malformed JSON; unknown extra field
Business rulesProduct out of stock; customer account suspended; order total above the allowed maximum
AuthenticationNo token; expired token; token with an invalid signature; token for another API (wrong audience)
AuthorizationMissing orders:write permission; ordering on behalf of another customer; client sets server-owned fields (status, customerId, total)
IdempotencySame Idempotency-Key and body gives one order; same key with a different body is rejected
ConcurrencyTwo orders for the last item in stock in parallel: exactly one succeeds
HTTP semanticsContent-Type: text/plain gives 415; Accept: application/xml gives 406; PUT /orders gives 405
Side effectsStock 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:

  1. POST /orders → 201, capture id
  2. GET /orders/{id} → 200, body equals what was sent
  3. PATCH /orders/{id} → 200; GET again shows the change persisted, unchanged fields untouched
  4. DELETE /orders/{id} → 204
  5. GET /orders/{id} → 404; a second DELETE → 404 (or 204, 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.

#DimensionWhat to testExpected
1Contract / schemaBody validates against the JSON schema from the spec; required fields present; types and formats (ISO 8601 dates, UUIDs, enums) correct; no undocumented or internal fieldsSchema passes
2Happy pathEvery documented success case, with optional fields both present and absent200 / 201 / 204 and correct body
3Input validationMissing, null, empty, wrong type, too short or long, out of range, invalid enum, malformed JSON, unknown fields, unicode, leading/trailing spaces400 with field-level detail, never 5xx
4Path and query parametersUnknown ID; malformed ID (abc where a UUID is expected); very long values; encoded and special characters (%2F, ../); invalid or repeated query params400 or 404, never 5xx
5Business rulesEach rule passing and failing; combinations of rules422 (or the documented code) with a specific error code
6AuthenticationNo credentials; malformed, expired, not-yet-valid, wrongly signed or revoked token; wrong issuer or audience401 with WWW-Authenticate, no data
7AuthorizationMissing 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
8Resource stateAllowed and forbidden transitions; operating on deleted or final-state resources409 for a wrong state
9Idempotency and retriesGET, PUT, DELETE repeated safely; POST with an idempotency key, replayed with the same and with a different bodyOne effect only
10ConcurrencyParallel updates to one resource; double submit; optimistic locking with ETag / If-MatchNo lost updates; 409 / 412 for the loser
11HTTP semantics and headers405 for wrong method; 415 wrong Content-Type; 406 unsupported Accept; Location on create; caching headers; CORS; correlation ID echoed; security headersCorrect codes and headers
12CollectionsPagination (first, middle, last, past the end, size 0, max size); sorting; filtering; empty results; stable orderingCorrect items and paging metadata
13Error formatAll errors follow one format (e.g. RFC 9457 Problem Details); no stack traces, SQL, class names or host namesConsistent, safe error body
14Side effects and consistencyRead-back after write; related resources updated; events or messages published; nothing changed after a rejected requestState matches the operation
15Resilience (component level)Dependency slow, down or returning errors (via WireMock); timeouts; retries; circuit breaker502 / 503 / 504 with a clean error, no hang

Status codes. Assert the exact, semantically correct code, not a range. A 200 where 201 is documented, or a 500 caused 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 stockAccount activeTotal within limitExpected
YesYesYes201
NoYesYes422 OUT_OF_STOCK
YesNoYes422 ACCOUNT_SUSPENDED
YesYesNo422 LIMIT_EXCEEDED
NoNoNo422 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.

OperationAnonymousCustomer (own order)Customer (other’s order)Support agentAdmin
GET /orders/{id}401200404200200
PATCH /orders/{id}401200404403200
DELETE /orders/{id}401403404403204

Turn each row and cell into a parameterised test (@MethodSource or @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.

LayerOwnsMust not containChanges when
TestsScenarios, expected outcomes, tagsURLs, tokens, raw JSON strings, HTTP configA requirement changes
Domain helpersEndpoint paths, request building, reusable assertions, fixturesExpectations about a specific scenarioThe API’s shape changes
InfrastructureBase URI, timeouts, auth, logging, reportingAnything about a specific resourceThe environment or auth setup changes

Tool choices

ConcernTool
HTTPREST Assured
Lifecycle, tags, parameterisation, parallelismJUnit Jupiter
Rich object assertionsAssertJ
(De)serialisationJackson
Contract checksjson-schema-validator
Async pollingAwaitility
Component levelTestcontainers and WireMock
ReportsAllure

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.java and 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 @DisplayName for 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.sleep to 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; float and double lose 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 Fixtures class 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

EnvironmentPurposeSuiteDependenciesDestructive tests
Local / CI componentFast feedback per commitFull, incl. resilienceTestcontainers for the database and broker; WireMock for external servicesYes
DEV / TESTReal integration with neighbouring servicesFull regressionReal services; sandboxes for third partiesYes
STAGINGRelease gate with production-like configSmoke + critical regressionProduction-likeLimited, with cleanup
PRODUCTIONPost-deployment checkRead-only smoke with a dedicated synthetic accountRealNever

Configuration and Secrets

  • One properties file per environment holds URLs and feature flags; TestConfig fails 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

TagMeaningRunsTime budget
smokeOne non-destructive happy path per critical operationAfter every deployment, incl. production (read-only subset)< 3 min
regressionFull functional and negative coverageEvery merge to main< 15 min
securityAuthentication, authorization, headersEvery merge and before every release< 10 min
resilienceFault injection with WireMockComponent stage only< 10 min
slowLong-running async flowsNightlyNo limit
quarantineKnown flaky, under investigation, excluded from gatesNightly, reported separatelyFix 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 @ResourceLock or @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"]
  1. Build and unit tests (surefire).
  2. Component tests: service started with Testcontainers and WireMock; full suite incl. resilience.
  3. Contract checks: OpenAPI validation and consumer pacts.
  4. Deploy to TEST: smoke first (stop if red), then regression and security.
  5. Deploy to STAGING: smoke plus critical regression as the release gate.
  6. 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

  1. Rerun once in CI only to detect flakiness, never to hide it; record every pass-on-retry.
  2. Quarantine with a ticket and an owner.
  3. Fix the root cause, which is usually shared data, timing (a missing poll) or order dependence.
  4. 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.

OperationRiskContractHappyValidationParamsRulesAuthNAuthZStateIdempotencyConcurrencyHTTPCollectionsErrorsSide effectsResilience
POST /ordersHigh   –       –   
GET /orders/{id}Medium  – –    – – – 
GET /ordersMedium    –  – –   – 
PATCH /orders/{id}High           –   
DELETE /orders/{id}High  –        –   
POST /orders/{id}/cancelHigh  –        –   

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, TokenProvider and 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.

This post is licensed under CC BY 4.0 by the author.