Sub topic 11
Testing without a network
Declarative clients are plain interfaces, so you can test them without starting a server. This chapter covers two levels of test. The first runs the generated client against canned HTTP responses. The second replaces the client with a mock when you test the code that calls it.
It assumes you have read the chapters on TodoClient, HttpServiceProxyFactory, and error handling. It also assumes you know JUnit 5 and AssertJ, and that spring-boot-starter-test is on the test classpath.
What you need to test
A declarative client has three parts that can break:
- The interface. Wrong paths, missing
@RequestParamnames, or the wrong HTTP method. - The conversion. JSON that does not map to your records, or request bodies that serialize differently than the API expects.
- The callers. Services that handle a 404 or a timeout from the client.
These need different tests. The first two need the real generated proxy, a real RestClient, and fake HTTP responses. The third only needs a stand-in for the interface.
| Goal | Tool | Real proxy | Real HTTP conversion |
|---|---|---|---|
| Check paths, verbs, headers, JSON mapping | `MockRestServiceServer` | Yes | Yes |
| Check how a service reacts to client results | Mockito mock of the interface | No | No |
| Check the real API contract | Integration test against a real or stubbed server | Yes | Yes |
How MockRestServiceServer works
MockRestServiceServer does not open a socket. It replaces the request factory inside a RestClient.Builder. Each request that the client makes is matched against the expectations you registered, and the mock returns the response you describe.
Because only the transport is replaced, everything above it is real. That includes URI template expansion, header handling, message converters, and status handlers. A typo in @GetExchange("/{id}") shows up in this kind of test.
A first test
The test builds its own RestClient.Builder, binds the mock server to it, and then builds the client. The order matters.
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.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath;
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.withStatus;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.util.List;
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.HttpClientErrorException;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
class TodoClientTest {
private MockRestServiceServer server;
private TodoClient client;
@BeforeEach
void setUp() {
RestClient.Builder builder = RestClient.builder().baseUrl("http://localhost");
server = MockRestServiceServer.bindTo(builder).build();
client = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(builder.build()))
.build()
.createClient(TodoClient.class);
}
@Test
void getsTodoById() {
server.expect(requestTo("http://localhost/todos/1"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(
"{\"id\":1,\"userId\":1,\"title\":\"write tests\",\"completed\":false}",
MediaType.APPLICATION_JSON));
Todo todo = client.getTodo(1);
assertThat(todo.title()).isEqualTo("write tests");
server.verify();
}
@Test
void sendsUserIdAsQueryParameter() {
server.expect(requestTo("http://localhost/todos?userId=7"))
.andRespond(withSuccess(
"[{\"id\":2,\"userId\":7,\"title\":\"ship\",\"completed\":true}]",
MediaType.APPLICATION_JSON));
List<Todo> todos = client.listByUser(7);
assertThat(todos).hasSize(1);
assertThat(todos.get(0).userId()).isEqualTo(7L);
server.verify();
}
@Test
void postsJsonBodyAndReadsStatus() {
server.expect(requestTo("http://localhost/todos"))
.andExpect(method(HttpMethod.POST))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.title").value("learn mocks"))
.andRespond(withStatus(HttpStatus.CREATED)
.contentType(MediaType.APPLICATION_JSON)
.body("{\"id\":201,\"userId\":1,\"title\":\"learn mocks\",\"completed\":false}"));
ResponseEntity<Todo> response =
client.create(new Todo(null, 1L, "learn mocks", false));
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(response.getBody().id()).isEqualTo(201L);
server.verify();
}
@Test
void mapsNotFoundToException() {
server.expect(requestTo("http://localhost/todos/99"))
.andRespond(withResourceNotFound());
assertThatThrownBy(() -> client.getTodo(99))
.isInstanceOf(HttpClientErrorException.NotFound.class);
server.verify();
}
}These tests cover several things:
- The first test checks the path template and JSON-to-record mapping.
- The second test checks that
@RequestParam long userIdbecomes the query string?userId=7. - The third test checks the request body. The
jsonPathmatcher reads what the client serialized, so it fails if a field is renamed or dropped. It also checks thatResponseEntity<Todo>exposes the status code. - The fourth test shows the default status handler at work. A 404 reaches the caller as
HttpClientErrorException.NotFound, with no extra code.
The spine's earlier example used the Java assert keyword. Plain assert does nothing unless the JVM runs with -ea, so a failing check can pass silently. Use AssertJ or JUnit assertions.
Why verify() matters
andRespond only runs if a request arrives. If the client never sends the call, no matcher fails and the test still passes, unless you call server.verify(). It fails the test if any registered expectation was never satisfied.
The failure modes are asymmetric:
- A request that does not match any expectation fails immediately, inside the client call, with an
AssertionErrorthat names the unexpected URI. - An expected request that never happens fails only at
verify().
Call verify() at the end of every test, or in an @AfterEach method.
Binding order and common errors
Most failures come from how the mock is wired, not from the matchers.
- Bind before you build.
bindTo(builder)installs the mock request factory on the builder. ARestClientcreated frombuilder.build()before binding keeps the real factory and sends real traffic. - The base URL must be in the expected URI. If the builder has
baseUrl("http://localhost"), expectations usehttp://localhost/todos/1. UsingrequestTo("/todos/1")fails. For shorter expectations you can userequestToUriTemplate("http://localhost/todos/{id}", 1). - Expectations are ordered by default. Requests must arrive in the order you declared them. Call
MockRestServiceServer.bindTo(builder).ignoreExpectOrder(true).build()if a service makes several independent calls. - One expectation matches one request. For repeated calls, use
server.expect(ExpectedCount.times(2), requestTo(...))orExpectedCount.manyTimes(). - Missing Content-Type breaks conversion.
withSuccess(body, MediaType.APPLICATION_JSON)sets the header. Without it, the client cannot choose a message converter and throws aRestClientExceptionabout an unsupported content type. - Mock only the builder you use. One
MockRestServiceServeris bound to one builder. If your configuration creates several clients, create a builder and a mock for each.
Testing the caller with a mock client
A service such as TodoService should not need HTTP to be tested. Since TodoClient is an interface, Mockito can mock it directly. This is the right level for logic around the client, such as "return null on 404".
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
class TodoServiceTest {
private final TodoClient client = mock(TodoClient.class);
private final TodoService service = new TodoService(client);
@Test
void returnsTodoWhenFound() {
Todo todo = new Todo(1L, 1L, "write tests", false);
when(client.getTodo(1)).thenReturn(todo);
assertThat(service.findOrNull(1)).isEqualTo(todo);
}
@Test
void returnsNullOnNotFound() {
when(client.getTodo(99)).thenThrow(HttpClientErrorException.create(
HttpStatus.NOT_FOUND, "Not Found", HttpHeaders.EMPTY, new byte[0], null));
assertThat(service.findOrNull(99)).isNull();
}
}HttpClientErrorException.create(...) returns the specific subclass for the status, so a 404 produces a NotFound and the catch block in TodoService runs. Building the exception by hand keeps the test small. It does not prove that the real client throws that type. The mapsNotFoundToException test above covers that, so you need both.
Slice tests and Spring Boot
You can also let Spring Boot wire the mock for you. A @RestClientTest slice test loads only RestClient-related infrastructure and exposes a MockRestServiceServer bound to the auto-configured RestClient.Builder. You then @Import your configuration class so the proxy is created from that same builder. Two details to watch:
- The annotation's package differs between Spring Boot 3.x and Spring Boot 4, because Boot 4 split its test support into modules. Check the import against your Boot version.
- The mock expects the full URL from your real configuration, for example
https://jsonplaceholder.typicode.com/todos/1.
The manual builder approach above avoids both issues and keeps the test independent of Boot. It is a good default for testing one client interface. Use the slice when you also want to check that your bean configuration, base URL properties, or customizers are applied.
If you register clients with @ImportHttpServices on Spring Boot 4, the same rule holds: the mock must be attached to the builder that creates the group's client before that client is built.
A short checklist
- Create a builder with the same base URL as production.
- Call
MockRestServiceServer.bindTo(builder).build(). - Build the proxy from
builder.build(). - Register expectations, then call the client.
- Assert on the result, and call
server.verify(). - Test callers separately with a Mockito mock of the interface.
Exercise
A test for client.listByUser(7) registers server.expect(requestTo("http://localhost/todos?userId=7")) with a canned response. The test calls client.listByUser(8) by mistake. At which point does the test fail, and what would happen if the test did not call server.verify() and never called the client at all?
Show answer
With listByUser(8), the request does not match the registered expectation, so it fails immediately inside the client call with an AssertionError about the unexpected URI /todos?userId=8. If the test never called the client and skipped server.verify(), it would pass silently, because no request arrived to fail a matcher. verify() is what fails a test whose expected request never happened.
Exercise
Why does this setup send real network traffic instead of using the mock? RestClient.Builder builder = RestClient.builder().baseUrl("http://localhost"); RestClient restClient = builder.build(); MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
Show answer
builder.build() runs before bindTo(builder). The mock replaces the request factory on the builder, so a RestClient built earlier keeps the real factory. Bind the mock first, then call builder.build() and pass that client to RestClientAdapter.create(...).