Sub topic 11
Testing client code
This chapter assumes you can write JUnit 5 tests with AssertJ and that you have built a RestClient as in the earlier chapters. You need spring-boot-starter-test and a JSON library such as Jackson on the test classpath.
Why not call the real API
A test that calls https://api.example.com is slow and breaks when the network or the remote service does. It also cannot reliably produce a 404 or a malformed body. MockRestServiceServer solves this by replacing the HTTP transport of a RestClient. Your code runs unchanged, but no socket is opened. The mock checks each outgoing request against your expectations and returns a canned response.
Binding the mock to the builder
Order matters. Call MockRestServiceServer.bindTo(builder) before builder.build(). Binding swaps the builder's request factory for the mock one. If you build the client first, the mock is never used and the test makes a real call.
A complete test class
The class below tests a small client that maps a 404 to a domain exception. It covers a success case and an error case.
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.withResourceNotFound;
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.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
record Todo(long id, String title, boolean completed) {}
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 findOrThrow(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.onStatus(status -> status.value() == HttpStatus.NOT_FOUND.value(),
(request, response) -> {
throw new TodoNotFoundException(id);
})
.body(Todo.class);
}
}
class TodoClientTest {
private MockRestServiceServer server;
private TodoClient todoClient;
@BeforeEach
void setUp() {
RestClient.Builder builder = RestClient.builder()
.baseUrl("https://api.example.com")
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
server = MockRestServiceServer.bindTo(builder).build();
todoClient = new TodoClient(builder.build());
}
@Test
void returnsTodoForKnownId() {
server.expect(requestTo("https://api.example.com/todos/1"))
.andExpect(method(HttpMethod.GET))
.andExpect(header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE))
.andRespond(withSuccess(
"{\"id\":1,\"title\":\"Write docs\",\"completed\":false}",
MediaType.APPLICATION_JSON));
Todo todo = todoClient.findOrThrow(1);
assertThat(todo).isEqualTo(new Todo(1, "Write docs", false));
server.verify();
}
@Test
void mapsNotFoundToDomainException() {
server.expect(requestTo("https://api.example.com/todos/99"))
.andRespond(withResourceNotFound());
assertThatThrownBy(() -> todoClient.findOrThrow(99))
.isInstanceOf(TodoNotFoundException.class)
.hasMessage("Todo 99 not found");
server.verify();
}
}What each part does
requestTo(...)matches the full expanded URL, so it also checks that the base URL and the URI template variable were applied correctly.andExpect(...)adds more checks on the same request. The matchersmethod,headerandcontent().json(...)are the ones you will use most.andRespond(...)takes a response creator.withSuccessreturns 200 with a body.withResourceNotFound,withServerErrorandwithStatus(HttpStatus)produce error responses.server.verify()fails the test if an expected request never happened. Without it, a test passes even when your code skips the call.
By default the server expects requests in the order you declared them, and an unexpected request fails immediately with an AssertionError. Use MockRestServiceServer.bindTo(builder).ignoreExpectOrder(true).build() when order is not part of the behavior.
Testing a request body
For POST and PUT, assert on the JSON your code sends. Add .andExpect(content().json("{\"title\":\"Buy milk\"}")) after importing MockRestRequestMatchers.content. The match is lenient about field order and whitespace, so refactors of the record do not break the test unnecessarily.
Using a Spring Boot slice test
@RestClientTest(TodoClient.class) starts a minimal context and auto-configures a MockRestServiceServer that you can inject. This works only if the class under test receives a RestClient.Builder and calls build() itself. A component that receives an already built RestClient bean gets no mock. The plain approach shown above avoids that coupling and starts faster.
Exercise
A test binds MockRestServiceServer to a builder, but its requests still go to the network. The code calls RestClient client = builder.build(); and then MockRestServiceServer.bindTo(builder).build();. What is wrong, and how do you fix it?
Show answer
The client was built before the mock was bound, so it already holds the real request factory. Call MockRestServiceServer.bindTo(builder).build() first and call builder.build() afterwards.
Exercise
Why should a test that uses expect(...) end with server.verify()?
Show answer
The mock only fails on requests it did not expect. It does not fail when an expected request never happens. verify() asserts that every expectation was met, so a test cannot pass after the code skips the call.