Sub topic 13
Testing JSON mapping and HTTP clients
This chapter assumes you know how Jackson maps Java objects to JSON, and that you have used RestClient or RestTemplate to call another service. It also assumes you have seen test slices such as @WebMvcTest. Two more slices cover code that sits at the edges of your application: @JsonTest for JSON mapping and @RestClientTest for HTTP clients.
Why test these separately
A controller test only proves JSON mapping works for the shapes it happens to send. Mapping rules like date formats, renamed fields, and ignored properties deserve their own fast tests. Likewise, a class that calls a remote API should be tested without a real network. Both slices load a small part of the context, so they stay fast.
Testing JSON with @JsonTest
@JsonTest loads only Jackson auto-configuration, including your ObjectMapper settings and any @JsonComponent classes. It gives you JacksonTester<T>, which serializes and deserializes objects and offers AssertJ-style assertions on the result.
Assume this record:
public record Greeting(String name, @JsonProperty("text") String message) {
}The test checks both directions:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;
@JsonTest
class GreetingJsonTest {
@Autowired
JacksonTester<Greeting> json;
@Test
void serializesMessageAsText() throws Exception {
Greeting greeting = new Greeting("Ada", "Hello, Ada");
assertThat(json.write(greeting)).hasJsonPathStringValue("$.text");
assertThat(json.write(greeting)).extractingJsonPathStringValue("$.text")
.isEqualTo("Hello, Ada");
}
@Test
void readsJson() throws Exception {
String content = "{\"name\":\"Ada\",\"text\":\"Hello, Ada\"}";
assertThat(json.parse(content)).isEqualTo(new Greeting("Ada", "Hello, Ada"));
}
}write returns a JsonContent, which supports JSONPath checks. parse returns an ObjectContent, which you compare with isEqualTo. Because the tester uses the application's configured ObjectMapper, a property such as spring.jackson.default-property-inclusion is honored.
Testing HTTP clients with @RestClientTest
@RestClientTest loads the beans needed for a client, such as RestClient.Builder or RestTemplateBuilder, and auto-configures a MockRestServiceServer. That object stands in for the remote server. You declare the expected request and the canned response, then call your client.
Assume a client class that wraps RestClient:
import org.springframework.boot.web.client.RestClientBuilderConfigurer;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
@Service
public class GreetingClient {
private final RestClient restClient;
public GreetingClient(RestClient.Builder builder) {
this.restClient = builder.baseUrl("https://greetings.example.com").build();
}
public Greeting fetch(String name) {
return restClient.get().uri("/greetings/{name}", name)
.retrieve().body(Greeting.class);
}
}The test names the client under test:
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.test.web.client.MockRestServiceServer;
@RestClientTest(GreetingClient.class)
class GreetingClientTest {
@Autowired
GreetingClient client;
@Autowired
MockRestServiceServer server;
@Test
void fetchesGreeting() {
server.expect(requestTo("https://greetings.example.com/greetings/Ada"))
.andRespond(withSuccess("{\"name\":\"Ada\",\"text\":\"Hello, Ada\"}",
MediaType.APPLICATION_JSON));
assertThat(client.fetch("Ada").message()).isEqualTo("Hello, Ada");
server.verify();
}
}server.verify() fails the test if an expected request never happened.
Common errors
- The client constructor takes a
RestClient.Builderbut the test fails to find a bean. Inject the builder, not a ready-madeRestClientbean, so the slice can attach the mock server to it. - The test sets a full URL in
requestTobut the client uses a different base URL. Compare the exact string the client builds. @JsonTestfails with a missingJacksonTester. Check that the test class carries the annotation and that you did not use plain JUnit.- A
MockRestServiceServertest passes without calling the client. Callserver.verify().
Exercise
Why does GreetingClient accept RestClient.Builder in its constructor instead of building its own RestClient with RestClient.create()?
Show answer
@RestClientTest binds MockRestServiceServer to the auto-configured RestClient.Builder. A client that creates its own RestClient bypasses that builder, so requests go to the real network and the mock server never sees them.