Sub topic 11
Testing without a network
This chapter assumes you know Java 17, basic Spring Boot (beans, @Configuration, injection), and JUnit. You should also have the TodoClient interface and the HttpServiceProxyFactory setup from the earlier chapters.
A declarative client is only an interface. The real work happens in the generated proxy and the RestClient behind it. A good test checks that the annotations produce the right request and that the response is converted into the right Java object. It should do this without calling a real server.
The idea: replace the transport, keep the proxy
MockRestServiceServer swaps the HTTP layer of a RestClient for a fake. You bind it to a RestClient.Builder, declare which requests you expect, and say what to answer. The proxy, the argument binding and the JSON conversion all run for real.
A first test
The order of steps matters. Bind the mock server to the builder first, then build the RestClient from that same builder.
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.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
class TodoClientTest {
@Test
void getsTodo() {
RestClient.Builder builder = RestClient.builder().baseUrl("http://localhost");
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
server.expect(requestTo("http://localhost/todos/1"))
.andRespond(withSuccess(
"{\"id\":1,\"userId\":1,\"title\":\"write tests\",\"completed\":false}",
MediaType.APPLICATION_JSON));
TodoClient client = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(builder.build()))
.build()
.createClient(TodoClient.class);
Todo todo = client.getTodo(1);
server.verify();
assert todo.title().equals("write tests");
}
}What this test proves:
@GetExchange("/{id}")plus the type-level/todosproduce the path/todos/1.- The
@PathVariableargument is substituted into the URI. - The JSON body is converted to a
Todorecord. server.verify()fails the test if an expected request never happened.
Checking more than the URL
requestTo is one of several matchers. Use method, header, queryParam and content().json(...) from MockRestRequestMatchers to check the rest of the request. This is how you test @PostExchange bodies and @RequestHeader bindings.
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
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 org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
// inside a test, after binding the server to the builder
server.expect(requestTo("http://localhost/todos"))
.andExpect(method(HttpMethod.POST))
.andExpect(content().json("{\"title\":\"write tests\",\"completed\":false}"))
.andRespond(withStatus(HttpStatus.CREATED)
.contentType(MediaType.APPLICATION_JSON)
.body("{\"id\":2,\"userId\":1,\"title\":\"write tests\",\"completed\":false}"));Testing error handling
Error responses are easy to simulate. withStatus and withResourceNotFound return the status you choose, so you can check the exception mapping from the error handling chapter.
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withResourceNotFound;
@Test
void returnsNullWhenMissing() {
RestClient.Builder builder = RestClient.builder().baseUrl("http://localhost");
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
server.expect(requestTo("http://localhost/todos/99")).andRespond(withResourceNotFound());
TodoClient client = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(builder.build()))
.build()
.createClient(TodoClient.class);
TodoService service = new TodoService(client);
assertNull(service.findOrNull(99));
server.verify();
}Common mistakes
- Building the
RestClientbefore binding. If you callbuilder.build()first, the mock never sees the requests, and the test tries a real connection. - Forgetting
server.verify(). Without it, a request that never happened goes unnoticed. - Using a different builder. The server must bind to the exact builder that creates the
RestClient. - Bare
assertstatements. Java ignoresassertunless you run with-ea. Prefer JUnit'sassertEqualsin real projects.
Exercise
A test binds MockRestServiceServer to a builder, but the call to the client fails with a connection error to localhost. The RestClient was built before MockRestServiceServer.bindTo(builder) ran. What is wrong, and how do you fix it?
Show answer
Binding changes the builder so that it uses the mock request factory. A RestClient built before binding keeps the real HTTP transport, so it opens a real connection. Call bindTo(builder).build() first, then call builder.build() to create the RestClient, and pass that to RestClientAdapter.create.