Post

Test Asynchronous APIs With REST Assured

Wait for asynchronous work without Thread.sleep, covering 202 Accepted, polling a Location with Awaitility, respecting Retry-After, and waiting for any final state before checking which one.

Test Asynchronous APIs With REST Assured

Executing a payment takes time, so the API doesn’t keep the connection open while it happens: it answers 202 Accepted at once, and does the work in the background. The test still needs the outcome. The first thing everyone tries is Thread.sleep(1000) and a check afterwards. On a fast machine, that wastes most of a second per test; on a busy CI agent, one second is sometimes not enough, and the test fails in a way nobody can reproduce. Both problems have the same fix. In this guide, you’ll poll until the work is done, with a timeout, and fail fast when it ends the wrong way.

Level: Advanced · Time: 20 minutes · Part of: Module 9: Data-Driven Tests and API Workflows, section 5

What You’ll Build

You’ll build a test class called AsyncPollingTest with three tests. One polls the payment’s Location until it’s executed, one waits as long as Retry-After asks before polling, and one waits for any final state and then checks which one it was.

Each test starts from the API’s answer to an execution:

1
2
3
4
5
6
7
POST /api/v1/payments/pay-11/execution HTTP/1.1

HTTP/1.1 202 Accepted
Location: /api/v1/payments/pay-11
Retry-After: 1

{"paymentId":"pay-11","status":"EXECUTING",...}

When you’re done, Maven reports three passing tests:

1
2
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Poll for the result.
  • Wait for any final state.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create AsyncPollingTest in a new section_05 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (AsyncPollingTest.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 doesn’t cover push-based results, such as webhooks or server-sent events; it polls.

Understand Asynchronous API Tests

The problem. An asynchronous API answers before the work is done, so the test must wait for an outcome it can’t see yet. A fixed sleep is either too short, a flaky test, or too long, a slow suite, and usually both on different machines.

The concept. 202 Accepted means the request was accepted for processing, which has started but not finished. A good asynchronous API also says where to look for the result, in Location, and how long to wait before asking, in Retry-After. Awaitility is a library for waiting in tests: it polls a condition until it holds, and fails with a clear message when a timeout passes.

AwaitilityWhat it does
atMost(..)The timeout
pollInterval(..)The time between attempts
pollDelay(..)The time before the first attempt
untilAsserted(lambda)Repeats the lambda until it stops throwing AssertionError
until(supplier, matcher)Repeats the supplier until its value matches, and returns the value

When to use each. Use untilAsserted(..) with a REST Assured check when one outcome is expected. Use until(..) to wait for the work to finish, whatever the outcome, and then check which outcome it was. Start with pollDelay(..) when the API sends Retry-After.

Wait until the work is finished, not for a fixed time, and not only for the outcome you hope for.

Meet the API Under Test

POST /api/v1/payments/{id}/execution on an authorised payment answers 202 Accepted, with status: EXECUTING, a Location and Retry-After: 1. About half a second later, the payment at the Location is:

AmountFinal statusrejectionReason
Up to 5000.00EXECUTEDnone
Above 5000.00REJECTEDINSUFFICIENT_FUNDS

Your tests check these values:

  • The Location and Retry-After headers of the 202.
  • The status at the Location, until it’s no longer EXECUTING.

Poll for the Result

Set Up the Test Class

Goal: create the test class with the API and a helper that starts an execution.

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_05;

import static com.javanibble.module_09.support.PaymentsClient.createPayment;
import static com.javanibble.module_09.support.PaymentsClient.spec;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.oneOf;
import static org.junit.jupiter.api.Assertions.assertEquals;

import com.javanibble.lifecycle.PaymentLifecycleApi;

import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;

import java.time.Duration;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class AsyncPollingTest {

    private static PaymentLifecycleApi api;

    @BeforeAll
    static void startApi() {
        api = PaymentLifecycleApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static ExtractableResponse<Response> startExecution(String amount) {
        String id = createPayment(api, amount);
        given(spec(api)).when().post("/payments/{id}/authorisation", id).then().statusCode(200);
        return given(spec(api)).when().post("/payments/{id}/execution", id).then().statusCode(202).extract();
    }
}

What’s happening:

  • startExecution(..) creates, authorises and executes a payment, and returns the 202 response, so each test reads its Location and Retry-After.
  • Each test gets its own payment, so the tests are independent.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Poll the Location Until the Work Is Done

Goal: wait for the payment to be executed, as long as it takes and no longer.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void pollTheLocationUntilTheWorkIsDone() {
    ExtractableResponse<Response> accepted = startExecution("40.00");
    String location = accepted.header("Location");

    await()
        .atMost(Duration.ofSeconds(5))
        .pollInterval(Duration.ofMillis(100))
        .untilAsserted(() ->
            given(spec(api)).basePath("").when().get(location)
                .then().body("status", equalTo("EXECUTED")));
}

What’s happening:

  • untilAsserted(..) runs the lambda again and again. An AssertionError means “not yet”, so a REST Assured check fits directly.
  • It polls every 100 milliseconds for up to five seconds. The test finishes as soon as the status is EXECUTED, about half a second here; the five seconds only matter when something is wrong.
  • The Location is an absolute path, so basePath("") clears the specification’s base path.

Checkpoint: run AsyncPollingTest from your IDE. One test runs and passes.

When the condition never holds, Awaitility fails with the last assertion error. Polling a 9000.00 payment for EXECUTED, with atMost(Duration.ofSeconds(2)), failed after 2,050 milliseconds with:

1
2
3
4
5
6
org.awaitility.core.ConditionTimeoutException: Assertion condition defined as a Lambda expression in ...
1 expectation failed.
JSON path status doesn't match.
Expected: EXECUTED
  Actual: REJECTED
 within 2 seconds.

The module’s spec(api) logs every failed validation, and inside untilAsserted(..), every “not yet” is a failed validation. In the passing run of this class, four full request and response logs were printed, though no test failed. Poll with until(supplier, matcher), which doesn’t validate with REST Assured, or with a specification without that log setting, as in Exercise 2.

Respect Retry-After

Goal: wait as long as the server asks before the first poll.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void respectRetryAfter() {
    ExtractableResponse<Response> accepted = startExecution("40.00");
    Duration retryAfter = Duration.ofSeconds(Long.parseLong(accepted.header("Retry-After")));
    String location = accepted.header("Location");

    await()
        .pollDelay(retryAfter)                                     // don't ask before the server said to
        .atMost(retryAfter.plusSeconds(5))
        .until(() -> given(spec(api)).basePath("").when().get(location).path("status"),
               oneOf("EXECUTED", "REJECTED"));
}

What’s happening:

  • Retry-After: 1 asks for one second, so pollDelay(retryAfter) waits one second before the first attempt.
  • atMost(..) includes the delay, so it’s the delay plus five seconds.
  • until(supplier, matcher) gets the status from the supplier, and checks it with the Hamcrest matcher oneOf(..).

Checkpoint: run the class again. Two tests pass.

Against a real service, polling every 100 milliseconds can count against a rate limit, and is rude besides. Honour Retry-After with pollDelay(..), and choose a pollInterval(..) that fits the service.

Wait for Any Final State

Check Which Outcome It Was

Goal: wait for the work to finish, whatever the outcome, and then check the outcome.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void waitForAFinalStateThenCheckWhichOne() {
    ExtractableResponse<Response> accepted = startExecution("9000.00");
    String location = accepted.header("Location");

    String finalStatus = await()
        .atMost(Duration.ofSeconds(5))
        .until(() -> given(spec(api)).basePath("").when().get(location).<String>path("status"),
               status -> !status.equals("EXECUTING"));

    assertEquals("REJECTED", finalStatus);
}

What’s happening:

  • The predicate is “anything but EXECUTING”, a plain lambda, which is clearer in Java than as a matcher.
  • until(..) returns the value that met the condition, so the test needs no extra request to read the final status.
  • 9000.00 is above the funds, so the payment ends REJECTED.

Checkpoint: run the class again. All three tests pass.

This is the most robust pattern. Waiting for EXECUTED on this payment keeps polling for a state that never comes, and fails only after the full timeout, as the ConditionTimeoutException above shows. Waiting for any final state fails as soon as the work ends, with a precise message.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-09 -Dtest=AsyncPollingTest

You should see a result similar to the following, after the logs of the failed polls:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_09.section_05.AsyncPollingTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.629 s -- in com.javanibble.module_09.section_05.AsyncPollingTest
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Most of the 2.6 seconds is the Retry-After delay; the other tests take about as long as the settlement.

Make a Test Fail

In waitForAFinalStateThenCheckWhichOne, change assertEquals("REJECTED", finalStatus) to expect "EXECUTED", and run the command again. You should see a result similar to the following:

1
2
[ERROR] Failures:
[ERROR]   AsyncPollingTest.waitForAFinalStateThenCheckWhichOne:86 expected: <EXECUTED> but was: <REJECTED>

The test failed in under a second, as soon as the payment settled, and the message names the real outcome. Waiting for EXECUTED directly would have failed only after five seconds.

Put "REJECTED" back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
ConditionTimeoutException ... within 5 secondsThe work ended in another state, or didn’t finish in timeWait for any final state, then check which; or raise atMost(..)
A passing test prints request logsuntilAsserted(..) with a specification that logs failed validationsUse until(..), or a quiet polling specification
404 with /api/v1/api/v1/..The Location with the base path still setAdd basePath("")
Tests fail on a slow agent but pass locallyA Thread.sleep(..) or a tight timeoutPoll with Awaitility, with a generous atMost(..)

Try It Yourself

Exercise 1: Return the Whole Response

Add a test called waitForTheWholeResponse. Execute a 9000.00 payment, and use until(..) with a supplier that returns the whole Response and a predicate on its status. Then check, on the returned response, that the status is REJECTED and the rejectionReason is INSUFFICIENT_FUNDS.

Hint

The supplier is () -> given(spec(api)).basePath("").when().get(location), and the predicate response -> !"EXECUTING".equals(response.path("status")). until(..) returns the Response, so use then() on it.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void waitForTheWholeResponse() {
    String location = startExecution("9000.00").header("Location");

    Response done = await()
        .atMost(Duration.ofSeconds(5))
        .until(() -> given(spec(api)).basePath("").when().get(location),
               response -> !"EXECUTING".equals(response.path("status")));

    done.then()
        .body("status", equalTo("REJECTED"))
        .body("rejectionReason", equalTo("INSUFFICIENT_FUNDS"));
}

Exercise 2: Poll Quietly

Add a test called pollQuietly. Build a polling specification with the base URI, the port and the Authorization header, but no base path and no log setting. Use it in untilAsserted(..) to wait for a 40.00 payment to be EXECUTED, and check that nothing is logged.

Hint

Build it with new RequestSpecBuilder(). Without a base path, the Location works as it is. You need imports for RequestSpecBuilder and RequestSpecification.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void pollQuietly() {
    RequestSpecification polling = new RequestSpecBuilder()
        .setBaseUri(api.baseUri()).setPort(api.port())
        .addHeader("Authorization", "Bearer " + PaymentLifecycleApi.TOKEN)
        .build();
    String location = startExecution("40.00").header("Location");

    await()
        .atMost(Duration.ofSeconds(5))
        .pollInterval(Duration.ofMillis(100))
        .untilAsserted(() ->
            given(polling).when().get(location).then().body("status", equalTo("EXECUTED")));
}

Add import io.restassured.builder.RequestSpecBuilder; and import io.restassured.specification.RequestSpecification; to the class. In a check, the same wait with spec(api) printed four request and response logs; with polling, it printed none.

Summary

You built AsyncPollingTest, which polls a payment’s Location until it’s executed, honours Retry-After before the first poll, and waits for any final state before checking which one. No test sleeps, and each takes about as long as the settlement.

  • 202 Accepted means the work has started, not finished; Location and Retry-After say where and when to look.
  • Awaitility polls until a condition holds, so a test takes as long as the work does, and fails with a clear message after a timeout.
  • Use untilAsserted(..) for REST Assured checks, and until(supplier, matcher) for values; until(..) returns the value it waited for.
  • Honour Retry-After with pollDelay(..), and keep atMost(..) generous: a passing test never waits for it.
  • Wait for any final state before checking which one, so a wrong outcome fails fast.

Here are the commands you used in this guide:

1
mvn test -pl module-09 -Dtest=AsyncPollingTest

What’s Next

Next: you’ve finished Module 9. Continue with Module 10: Stubbing Dependencies with WireMock, starting with Stub a Dependency With WireMock in REST Assured Tests, which tests an API whose third-party dependency you don’t control.

The code:

Go deeper:

Related guides:

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