Post

Verify Outgoing Calls With WireMock in REST Assured Tests

Check the requests your API sends to a third party, covering verify(..) with an exact count, query parameters and headers, one retry for a 503, no retry for a 500, and reading recorded requests with findAll(..).

Verify Outgoing Calls With WireMock in REST Assured Tests

REST Assured checks what your API answers. That’s half the story. The other half is what your API sends to its dependency, and nothing in the response tells you. Did it send the API key, and the client id the provider bills by? Did it call the provider once per quote, or twice? Did it retry a temporary outage once, or hammer the provider? The quote can be perfect while every one of those is wrong. In this guide, you’ll read WireMock’s record of the calls your API made, and check the outgoing side too.

Level: Advanced · Time: 20 minutes · Part of: Module 10: Stubbing Dependencies with WireMock, section 3

What You’ll Build

You’ll build a test class called VerifyingCallsTest with four tests. One checks that a quote makes exactly one call with the right query and headers; two check that a 503 is retried once and a 500 isn’t; and one reads the recorded request itself.

When the count is wrong, WireMock says exactly what it received:

1
2
3
4
5
Expected exactly 1 requests matching the following pattern but received 2:
{
  "urlPath" : "/v2/rates",
  "method" : "GET"
}

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

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

In this guide, you will:

  • Verify the request.
  • Verify the retries.
  • Read the recorded requests.

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 VerifyingCallsTest in a new section_03 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (VerifyingCallsTest.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 Stub a Dependency With WireMock in REST Assured Tests.

Out of scope: this guide doesn’t cover recording a real provider’s traffic to create stubs, a WireMock feature of its own.

Understand Verifying Outgoing Calls

The problem. Some bugs live entirely on the outgoing side. A missing header, a duplicate call, a missing retry or a needless one: your API’s answer looks the same either way. A 503 and a 500 from the provider both reach your client as 502, so the response can’t show whether the service retried.

The concept. WireMock keeps a journal of every request it receives. Two methods read it:

  • verify(count, pattern) checks that exactly count requests matched the pattern, and fails with a clear message otherwise.
  • findAll(pattern) returns the matching requests as LoggedRequest objects, to check in any way you like.

The patterns start with getRequestedFor(..), postRequestedFor(..) and so on, and take the same withQueryParam(..) and withHeader(..) conditions as stubs. Strict stubs, from section 1, check the request too, but indirectly:

 A strict stubA loose stub with verify(..)
A wrong headerThe stub doesn’t match; WireMock answers 404The stub answers; verify(..) fails
The failure messageYour API’s reaction to a 404, pointing elsewhereWireMock’s closest request, showing the difference
Call countsNot checkedChecked exactly

When to use each. Use strict stubs when the request is a precondition, and a loose stub with a precise verify(..) when the request is what you’re testing. Always verify counts that cost money or load: retries, and calls per quote.

Check what your API sent, not only what it answered.

Meet the API Under Test

For a quote of 100.00 EUR in GBP, the quote service sends one request to the provider:

1
2
3
4
GET /v2/rates?base=EUR&symbols=GBP HTTP/1.1
Authorization: Bearer fx-api-key
X-Client-Id: payments-service
Accept: application/json

When the provider fails, the service decides whether to try again:

The provider answersCalls the service makesOur API answers
2001201
5032: the first try and one retry502
5001502
4291503

Your tests check these values:

  • The number of calls that reached the provider.
  • Their path, query parameters and headers.
  • The full URL of a recorded call.

Verify the Request

Set Up the Test Class

Goal: create the test class with WireMock, the service, and a helper that requests one quote.

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
package com.javanibble.module_10.section_03;

import static com.javanibble.module_10.support.FxProviderStubs.quoteRequest;
import static com.javanibble.module_10.support.FxProviderStubs.ratesBody;
import static com.javanibble.module_10.support.FxProviderStubs.ratesRequest;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;

import com.javanibble.fx.QuoteService;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;

import io.restassured.http.ContentType;

import java.util.List;

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

class VerifyingCallsTest {

    @RegisterExtension
    static WireMockExtension fxProvider = WireMockExtension.newInstance()
        .options(wireMockConfig().dynamicPort())
        .build();

    private static QuoteService service;

    @BeforeAll
    static void startService() {
        service = QuoteService.start(fxProvider.baseUrl());
    }

    @AfterAll
    static void stopService() {
        service.close();
    }

    private static void requestAQuote() {
        given().baseUri(service.baseUri()).port(service.port())
            .contentType(ContentType.JSON).body(quoteRequest("EUR", "GBP", "100.00"))
            .when().post("/api/v1/quotes");
    }
}

What’s happening:

  • requestAQuote() sends one quote with REST Assured, and doesn’t check the answer: these tests are about what happens behind it. Section 2 checked the answers.
  • WireMockExtension resets the journal after each test, as it does the stubs: at the start of the next test, the journal was empty. Counts in one test never include calls from another.

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

Check One Call With the Right Headers

Goal: prove a quote makes exactly one call, with every detail the provider requires.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void oneQuoteMeansExactlyOneCallWithTheRightHeaders() {
    // A deliberately loose stub, so the verification below is what checks the details.
    fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates"))
        .willReturn(WireMock.okJson(ratesBody("EUR", "GBP", "0.85"))));

    requestAQuote();

    fxProvider.verify(1, WireMock.getRequestedFor(WireMock.urlPathEqualTo("/v2/rates"))
        .withQueryParam("base", WireMock.equalTo("EUR"))
        .withQueryParam("symbols", WireMock.equalTo("GBP"))
        .withHeader("Authorization", WireMock.equalTo("Bearer " + QuoteService.API_KEY))
        .withHeader("X-Client-Id", WireMock.equalTo(QuoteService.CLIENT_ID))
        .withHeader("Accept", WireMock.equalTo("application/json")));
}

What’s happening:

  • The stub matches any GET /v2/rates, so the service always gets a rate, whatever it sends.
  • verify(1, ..) checks the one call that should have followed, with both query parameters and all three headers.
  • The count matters as much as the details: verify(1, ..) fails if the service called the provider twice, which would double the cost of every quote.

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

When a detail is wrong, WireMock shows the closest request it received. Verifying X-Client-Id: another-client failed with:

1
2
3
4
5
6
7
8
9
10
11
12
com.github.tomakehurst.wiremock.client.VerificationException:
No requests exactly matched. Most similar request was:  expected:<
GET
/v2/rates?base=EUR&symbols=GBP

X-Client-Id: another-client
> but was:<
GET
/v2/rates?base=EUR&symbols=GBP

X-Client-Id: payments-service
>

Always give the count. verify(pattern) without one means “at least once”: after two quotes, it passed, while verify(1, ..) failed with received 2. For counts other than exact, WireMock has exactly(..), lessThan(..) and moreThanOrExactly(..), as in verify(WireMock.exactly(2), ..).

Verify the Retries

Retry a Temporary Outage Once

Goal: prove the service retries a 503 exactly once.

Add this test to the class:

1
2
3
4
5
6
7
8
@Test
void aTemporaryOutageIsRetriedOnce() {
    fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.serviceUnavailable()));

    requestAQuote();

    fxProvider.verify(2, WireMock.getRequestedFor(WireMock.urlPathEqualTo("/v2/rates")));   // first try + one retry
}

What’s happening:

  • 503 Service Unavailable is temporary by definition, so the service tries again once.
  • The stub answers 503 both times, so the client gets 502 either way. Only the count shows the retry happened.
  • verify(2, ..) also proves the service stopped after one retry, instead of hammering the provider.

Checkpoint: run the class again. Two tests pass.

Don’t Retry Other Errors

Goal: prove a permanent error isn’t retried.

Add this test to the class:

1
2
3
4
5
6
7
8
@Test
void otherErrorsAreNotRetried() {
    fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.serverError()));

    requestAQuote();

    fxProvider.verify(1, WireMock.getRequestedFor(WireMock.urlPathEqualTo("/v2/rates")));
}

What’s happening:

  • A 500 isn’t a temporary condition, and retrying it adds load to a provider that’s already in trouble.
  • verify(1, ..) proves the service called once and gave up. Testing what must not happen matters as much as testing what must.

Checkpoint: run the class again. Three tests pass.

Read the Recorded Requests

Check a Request Yourself

Goal: get the recorded requests, for checks verify(..) can’t express.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
@Test
void readTheRecordedRequestsYourself() {
    fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.okJson(ratesBody("EUR", "GBP", "0.85"))));

    requestAQuote();

    List<LoggedRequest> calls = fxProvider.findAll(WireMock.getRequestedFor(WireMock.urlPathEqualTo("/v2/rates")));
    assertEquals(1, calls.size());
    assertEquals("/v2/rates?base=EUR&symbols=GBP", calls.getFirst().getUrl());
}

What’s happening:

  • findAll(..) returns the matching requests themselves, in the order they arrived.
  • getUrl() gives the path with its query string. A LoggedRequest also has getMethod(), getHeader(..), queryParameter(..), getBodyAsString() and getLoggedDate().
  • Use it to compare two requests with each other, or to parse a request body with JsonPath.from(..), from Read Many Values With JsonPath and XmlPath in REST Assured.

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

The journal also records headers you didn’t set. The service’s request arrived with User-Agent: Java-http-client/26.0.1, from the JDK’s HTTP client. Verify what the provider requires and what costs money, not every incidental header, or tests break on a JDK upgrade.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-10 -Dtest=VerifyingCallsTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_10.section_03.VerifyingCallsTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.449 s -- in com.javanibble.module_10.section_03.VerifyingCallsTest
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In aTemporaryOutageIsRetriedOnce, change verify(2, ..) to verify(1, ..), and run the command again. You should see a result similar to the following:

1
2
3
4
5
6
[ERROR] Failures:
[ERROR]   VerifyingCallsTest.aTemporaryOutageIsRetriedOnce:78 Expected exactly 1 requests matching the following pattern but received 2:
{
  "urlPath" : "/v2/rates",
  "method" : "GET"
}

WireMock names the pattern and the real count: two calls, the first try and the retry. This is the failure you’d see if someone removed a retry the test expected, or added one it didn’t.

Put verify(2, ..) back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
No requests exactly matched. Most similar request was: ..A query parameter or header differsCompare the expected and actual parts in the message
Expected exactly 1 requests .. but received 2A retry or a duplicate callDecide which count is right, and fix the service or the test
A duplicate call passesverify(pattern) without a count means “at least once”Give the exact count
Counts include another test’s callsA hand-started WireMockServer that isn’t resetUse WireMockExtension, or call resetAll() between tests

Try It Yourself

Exercise 1: Check the Recorded Headers

Add a test called theRecordedRequestCarriesTheClientId. Request a quote, get the one recorded call with findAll(..), and check that its X-Client-Id header is payments-service, its symbols query parameter is GBP, and its body is empty.

Hint

Use getHeader("X-Client-Id"), queryParameter("symbols").firstValue() and getBodyAsString() on the LoggedRequest. Import assertTrue for the empty body.

Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void theRecordedRequestCarriesTheClientId() {
    fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.okJson(ratesBody("EUR", "GBP", "0.85"))));

    requestAQuote();

    LoggedRequest call = fxProvider.findAll(WireMock.getRequestedFor(WireMock.urlPathEqualTo("/v2/rates"))).getFirst();
    assertEquals("payments-service", call.getHeader("X-Client-Id"));
    assertEquals("GBP", call.queryParameter("symbols").firstValue());
    assertTrue(call.getBodyAsString().isEmpty());
}

Add import static org.junit.jupiter.api.Assertions.assertTrue; to the class.

Exercise 2: Don’t Retry Rate Limiting

Add a test called rateLimitingIsNotRetried. Stub a 429 with Retry-After: 30, request a quote, and check that the service called the provider exactly once.

Hint

Build the answer with WireMock.aResponse().withStatus(429).withHeader("Retry-After", "30"). A provider that’s rate limiting asked to be left alone for 30 seconds; an immediate retry would ignore that.

Solution
1
2
3
4
5
6
7
8
9
@Test
void rateLimitingIsNotRetried() {
    fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(
        WireMock.aResponse().withStatus(429).withHeader("Retry-After", "30")));

    requestAQuote();

    fxProvider.verify(1, WireMock.getRequestedFor(WireMock.urlPathEqualTo("/v2/rates")));
}

Summary

You built VerifyingCallsTest, which checks the outgoing side of the quote service: exactly one call per quote with the right query and headers, one retry for a 503, none for a 500, and a recorded request read directly. The provider gets what it requires, and no more calls than it should.

  • WireMock records every request it receives; WireMockExtension resets the record after each test.
  • verify(count, pattern) checks the exact number of matching calls, with a message that shows the closest request or the real count.
  • Always give the count: verify(pattern) alone means “at least once”.
  • Verify what the response can’t show: retries, duplicate calls, and calls that must not happen.
  • findAll(..) returns the recorded requests, for checks verify(..) can’t express.

Here are the commands you used in this guide:

1
mvn test -pl module-10 -Dtest=VerifyingCallsTest

What’s Next

Next: continue with Use Response Templates and Scenarios in WireMock Stubs, which builds stubs that adapt to the request, and a provider that fails and recovers.

The code:

Go deeper:

Related guides:

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