Sub topic 11
Testing client code
This chapter shows how to test code that calls a remote API through RestClient without a network or a real server. It assumes you can read the RestClient calls from the earlier chapters and know JUnit 5 and AssertJ. It also assumes you know what a Spring test slice is.
What MockRestServiceServer does
MockRestServiceServer replaces the HTTP transport underneath a RestClient. Your client code runs unchanged: it expands URI templates, serializes bodies, runs interceptors, and converts JSON. The only part replaced is the step that sends bytes over the network. In its place, the mock checks each request against your expectations and returns a canned response.
The class has been usable with RestClient since Spring Framework 6.1. It is the same class used for RestTemplate, so existing knowledge carries over.
Binding order matters
The mock works by installing its own request factory on a RestClient.Builder. That means you must call bindTo(builder) before builder.build(). If you build the client first, the mock is never connected and the test tries to reach the real host.
Two consequences follow from how the binding works:
- Base URL, default headers, interceptors, and message converters set on the builder still apply. Interceptors still run, so you can test them.
- Any request factory you set on the builder, such as the timeout configuration from the earlier chapter, is replaced. The mock cannot tell you whether your timeouts work.
A complete example
The first listing is a small client with a lookup, a create call, and a mapped 404. The second listing is the test class. Both can be compiled together.
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClient;
record Todo(long id, String title, boolean completed) {}
record NewTodo(String title) {}
class TodoNotFoundException extends RuntimeException {
TodoNotFoundException(long id) {
super("Todo " + id + " not found");
}
}
class TodoClient {
private final RestClient restClient;
TodoClient(RestClient restClient) {
this.restClient = restClient;
}
Todo findById(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.onStatus(status -> status.value() == 404, (request, response) -> {
throw new TodoNotFoundException(id);
})
.body(Todo.class);
}
ResponseEntity<Void> create(NewTodo newTodo) {
return restClient.post()
.uri("/todos")
.contentType(MediaType.APPLICATION_JSON)
.body(newTodo)
.retrieve()
.toBodilessEntity();
}
}import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClient;
class TodoClientTest {
private MockRestServiceServer server;
private TodoClient client;
@BeforeEach
void setUp() {
RestClient.Builder builder = RestClient.builder()
.baseUrl("https://api.example.com")
.requestInterceptor((request, body, execution) -> {
request.getHeaders().setBearerAuth("test-token");
return execution.execute(request, body);
});
server = MockRestServiceServer.bindTo(builder).build();
client = new TodoClient(builder.build());
}
@Test
void findByIdMapsJsonToRecord() {
server.expect(requestTo("https://api.example.com/todos/1"))
.andExpect(method(HttpMethod.GET))
.andExpect(header("Authorization", "Bearer test-token"))
.andRespond(withSuccess(
"{\"id\":1,\"title\":\"Write docs\",\"completed\":false}",
MediaType.APPLICATION_JSON));
Todo todo = client.findById(1);
assertThat(todo).isEqualTo(new Todo(1, "Write docs", false));
server.verify();
}
@Test
void findByIdMapsNotFoundToDomainException() {
server.expect(requestTo("https://api.example.com/todos/99"))
.andRespond(withStatus(HttpStatus.NOT_FOUND));
assertThatExceptionOfType(TodoNotFoundException.class)
.isThrownBy(() -> client.findById(99))
.withMessage("Todo 99 not found");
}
@Test
void serverErrorSurfacesAsException() {
server.expect(requestTo("https://api.example.com/todos/2"))
.andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.TEXT_PLAIN)
.body("boom"));
assertThatExceptionOfType(HttpServerErrorException.class)
.isThrownBy(() -> client.findById(2))
.satisfies(e -> {
assertThat(e.getStatusCode().value()).isEqualTo(500);
assertThat(e.getResponseBodyAsString()).isEqualTo("boom");
});
}
@Test
void createSendsJsonBody() {
server.expect(requestTo("https://api.example.com/todos"))
.andExpect(method(HttpMethod.POST))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().json("{\"title\":\"Ship it\"}"))
.andRespond(withStatus(HttpStatus.CREATED));
ResponseEntity<Void> response = client.create(new NewTodo("Ship it"));
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
server.verify();
}
}The tests check four things:
- The first test checks the URL, the method, the interceptor's
Authorizationheader, and the JSON-to-record mapping. - The second shows that a mapped status works end to end. The
onStatushandler throws your domain exception. - The third shows the default error path. A 5xx response becomes an
HttpServerErrorException, which is aRestClientResponseException, so it carries the status and body. - The fourth checks the outgoing body.
content().json(...)compares JSON structurally, so field order and whitespace do not matter. It needs the JSONassert library, whichspring-boot-starter-testincludes.
Expectations, ordering, and verify()
Each server.expect(...) registers one expected request. The default rules are strict:
| Behavior | Default | How to change it |
|---|---|---|
| Ordering | Requests must arrive in the order you declared the expectations. | `MockRestServiceServer.bindTo(builder).ignoreExpectOrder(true).build()` |
| Count | Each expectation matches once. | `server.expect(ExpectedCount.times(2), requestTo(...))` |
| Unexpected request | The client call fails with an `AssertionError` as soon as the request arrives. | Add an expectation. |
| Missing request | Nothing fails until you call `server.verify()`. | Always call `verify()`. |
A test that never calls verify() passes even when the code under test skipped a call. For tests with several expectations, call server.reset() between phases or create a new server per test, as @BeforeEach does above.
Simulating failures that are not HTTP statuses
Some failures occur before any status exists, such as a refused connection or a read timeout. The mock can simulate these with withException:
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withException;
import java.net.SocketTimeoutException;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
class TimeoutSimulation {
ResourceAccessException simulate() {
RestClient.Builder builder = RestClient.builder().baseUrl("https://api.example.com");
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
RestClient client = builder.build();
server.expect(requestTo("https://api.example.com/todos/1"))
.andRespond(withException(new SocketTimeoutException("Read timed out")));
try {
client.get().uri("/todos/{id}", 1).retrieve().body(String.class);
throw new IllegalStateException("expected a failure");
} catch (ResourceAccessException e) {
return e;
}
}
}RestClient wraps the IOException in a ResourceAccessException. Compare this with the earlier error-handling chapter. An HTTP error status becomes a RestClientResponseException. An I/O failure becomes a ResourceAccessException. Your retry or fallback code usually needs to treat these two differently, and the mock lets you test both branches.
Testing with Spring Boot's @RestClientTest
If the class under test receives a RestClient.Builder, Spring Boot 3.2 and later can do the binding for you. @RestClientTest loads only the beans you name plus the client infrastructure. It also registers a MockRestServiceServer bound to the auto-configured builder.
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
@Service
class TodoLookupService {
private final RestClient restClient;
TodoLookupService(RestClient.Builder builder) {
this.restClient = builder.baseUrl("https://api.example.com").build();
}
Todo findById(long id) {
return restClient.get().uri("/todos/{id}", id).retrieve().body(Todo.class);
}
}
@RestClientTest(TodoLookupService.class)
class TodoLookupServiceTest {
@Autowired
private TodoLookupService service;
@Autowired
private MockRestServiceServer server;
@Test
void findsTodo() {
server.expect(requestTo("https://api.example.com/todos/3"))
.andRespond(withSuccess(
"{\"id\":3,\"title\":\"Review\",\"completed\":true}",
MediaType.APPLICATION_JSON));
assertThat(service.findById(3).completed()).isTrue();
}
}Two details affect whether this works:
- The service must take
RestClient.Builder, not a finishedRestClientbean. The slice binds the mock to the builder, and a prebuilt client bean in your own configuration is not part of the slice unless you import it. - Boot's
RestClient.Builderbean is prototype-scoped, so each injection gets a fresh builder. The slice customizes that builder, which is why the mock is connected to the service's client.
If a slice test is not worth the setup, the plain JUnit style from the full example is simpler and faster. It needs no Spring context at all.
Testing HTTP interface clients
An @HttpExchange proxy sends its calls through the RestClient you hand to RestClientAdapter. To test the interface, bind the mock to the builder, build the client, and wrap it in the adapter. The proxy then sends its requests through the mock like any other call. This verifies your annotations: the path, the HTTP method, and how path variables map.
When to use something else
MockRestServiceServer tests your code up to the transport. It does not exercise a real HTTP stack.
| Need | Tool |
|---|---|
| Fast unit tests of mapping, error handling, and interceptors | `MockRestServiceServer` |
| Real sockets, real timeouts, connection resets, or TLS behavior | A local fake server such as WireMock or OkHttp `MockWebServer` |
| Confidence that the remote contract has not changed | Contract tests or a sandbox environment of the provider |
A common split is many mock-server tests for logic and a few local-server tests for transport behavior such as the timeouts you configured.
Common mistakes
- Building the client before
bindTo(builder). The mock never connects. - Forgetting
server.verify(), so missing calls go unnoticed. - Asserting on a full URL while the client has a base URL, then writing the relative path in
requestTo. Use the full expanded URL, or a matcher such asrequestTo(containsString("/todos/1")). - Expecting the mock to test timeouts. It replaces the request factory that carries them.
- Comparing JSON as raw strings with
content().string(...). Field order and spacing make such tests brittle, so prefercontent().json(...).
Exercise
A test builds a RestClient from a builder, then calls MockRestServiceServer.bindTo(builder).build(), then makes a request. The test tries to contact the real host. What is wrong, and how do you fix it?
Show answer
The client was built before the mock was bound. bindTo installs the mock request factory on the builder, so it only affects clients built afterward. Call bindTo(builder).build() first, then builder.build() to create the RestClient.
Exercise
Your client sets a 5-second read timeout through a JdkClientHttpRequestFactory. Why can a MockRestServiceServer test not prove that this timeout works, and what would you use instead?
Show answer
The mock replaces the builder's request factory, so the configured timeout is never used. To test it, point the client at a local fake HTTP server such as WireMock or MockWebServer that delays its response longer than the timeout, and assert that a ResourceAccessException is thrown. You can still test your handling of a timeout with withException(new SocketTimeoutException(...)).
Exercise
A test registers two expectations but the code under test only makes one of the two calls. The test still passes. What is missing?
Show answer
The test never calls server.verify(). Unexpected requests fail immediately, but expectations that were never met are only reported when verify() runs.