Sub topic 13
Testing JSON mapping and HTTP clients
This chapter covers two more test slices. @JsonTest checks how your classes become JSON and back. @RestClientTest checks code that calls other services over HTTP. Both load a small part of the application, so they start quickly. The examples assume Spring Boot 3.x with spring-boot-starter-test, JUnit 5, and AssertJ. You should already know how test slices work from the earlier chapters.
Why test these layers on their own
JSON mapping and HTTP clients both sit at the edge of your application. Both are easy to break by accident.
- A renamed record component changes the JSON field name. Every consumer of your API then breaks, and no unit test notices.
- A changed date format passes a service test and fails in production.
- A client that builds the wrong URL or ignores a
404response works in every test that mocks the client class itself.
A @WebMvcTest already exercises JSON through MockMvc, but it mixes JSON mapping with routing and validation. When a field name or date format is wrong, a dedicated JSON test points at the cause. A client test does the same for URLs, headers, and error handling.
| Slice | Loads | Test helper | Question it answers |
|---|---|---|---|
| `@JsonTest` | Jackson (or Gson, JSON-B) configuration | `JacksonTester<T>` | Does this object map to the JSON I expect, and back? |
| `@RestClientTest` | One client bean, `RestTemplateBuilder`, a mock server | `MockRestServiceServer` | Does my client send the right request and handle the response? |
The class under test
Both examples use this record. It is the same Greeting idea used in earlier chapters, with a date added so that date formatting is visible.
package com.example.greetings;
import java.time.LocalDate;
public record Greeting(String name, String message, LocalDate issuedOn) {
}Testing JSON mapping with @JsonTest
@JsonTest creates a Spring context containing only the JSON auto-configuration. It registers the ObjectMapper that your application would use, including any Jackson2ObjectMapperBuilderCustomizer beans, @JsonComponent classes, and spring.jackson.* properties. It also registers JacksonTester fields for injection. It starts no web server, loads no controllers, and does not touch the database.
package com.example.greetings;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.time.LocalDate;
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 serializesToExpectedJson() throws IOException {
Greeting greeting = new Greeting("Ada", "Hello, Ada", LocalDate.of(2026, 12, 1));
assertThat(json.write(greeting)).extractingJsonPathStringValue("$.name").isEqualTo("Ada");
assertThat(json.write(greeting)).extractingJsonPathStringValue("$.issuedOn").isEqualTo("2026-12-01");
}
@Test
void deserializesFromJson() throws IOException {
String content = """
{"name": "Ada", "message": "Hello, Ada", "issuedOn": "2026-12-01"}
""";
assertThat(json.parse(content))
.isEqualTo(new Greeting("Ada", "Hello, Ada", LocalDate.of(2026, 12, 1)));
}
}Some details about this test:
json.write(...)returns aJsonContent. AssertJ'sassertThataccepts it and gives you JSON-aware assertions such asextractingJsonPathStringValue,hasJsonPathStringValue, andisEqualToJson.json.parse(...)returns anObjectContent. Compare it to an object directly, or callgetObject()for the instance.- The date appears as
"2026-12-01"because Spring Boot turns offWRITE_DATES_AS_TIMESTAMPSby default. A plainnew ObjectMapper()would write an array or fail onLocalDate. This is why you inject the tester and do not build your own mapper. isEqualToJsonuses lenient comparison by default. Extra fields and a different field order still pass. PassJSONCompareMode.STRICTwhen the exact shape matters.
Testing the effect of configuration
@JsonTest accepts a properties attribute, so you can check that a Jackson setting does what you think.
package com.example.greetings;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.time.LocalDate;
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(properties = "spring.jackson.property-naming-strategy=SNAKE_CASE")
class SnakeCaseGreetingJsonTest {
@Autowired
JacksonTester<Greeting> json;
@Test
void usesSnakeCaseFieldNames() throws IOException {
Greeting greeting = new Greeting("Ada", "Hello, Ada", LocalDate.of(2026, 12, 1));
assertThat(json.write(greeting)).hasJsonPathStringValue("$.issued_on");
assertThat(json.write(greeting)).doesNotHaveJsonPathValue("$.issuedOn");
}
}Use this pattern when your application sets a global naming strategy or a date format. If an annotation such as @JsonProperty or @JsonFormat is the only thing that fixes a field's name or format, test that class once and leave the global setting out.
Testing HTTP clients with @RestClientTest
A client class wraps calls to another service. It should be tested without a network. @RestClientTest loads the client bean you name, RestTemplateBuilder, Jackson, and a MockRestServiceServer. The mock server replaces the HTTP transport. Your client still builds a real request and parses a real response body, but no socket opens.
This is the client:
package com.example.greetings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class GreetingClient {
private final RestTemplate restTemplate;
public GreetingClient(RestTemplateBuilder builder, @Value("${greeting.base-url}") String baseUrl) {
this.restTemplate = builder.rootUri(baseUrl).build();
}
public Greeting fetch(String name) {
return restTemplate.getForObject("/greetings/{name}", Greeting.class, name);
}
}The client must receive its RestTemplateBuilder from Spring and call build() on it. The test infrastructure customizes that builder, so any template it produces talks to the mock server. A client that calls new RestTemplate() bypasses the customization and attempts a real connection. Since Spring Boot 3.2, the same approach works with an injected RestClient.Builder.
package com.example.greetings;
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.withStatus;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.time.LocalDate;
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.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.HttpClientErrorException;
@RestClientTest(value = GreetingClient.class, properties = "greeting.base-url=http://greetings.example")
class GreetingClientTest {
@Autowired
GreetingClient client;
@Autowired
MockRestServiceServer server;
@Test
void fetchesGreeting() {
server.expect(requestTo("http://greetings.example/greetings/Ada"))
.andExpect(method(HttpMethod.GET))
.andExpect(header("Accept", "application/json, application/*+json"))
.andRespond(withSuccess(
"{\"name\":\"Ada\",\"message\":\"Hello, Ada\",\"issuedOn\":\"2026-12-01\"}",
MediaType.APPLICATION_JSON));
Greeting greeting = client.fetch("Ada");
assertThat(greeting).isEqualTo(new Greeting("Ada", "Hello, Ada", LocalDate.of(2026, 12, 1)));
server.verify();
}
@Test
void reportsMissingGreeting() {
server.expect(requestTo("http://greetings.example/greetings/Nobody"))
.andRespond(withStatus(HttpStatus.NOT_FOUND));
assertThatThrownBy(() -> client.fetch("Nobody"))
.isInstanceOf(HttpClientErrorException.NotFound.class);
}
}What the test proves
- Request shape.
requestTo,method,header, and the body matchers assert what your client sends. By default the server expects calls in the order you declared them. - Response handling. The canned body goes through your real
HttpMessageConverterchain, so mapping problems appear here. - Error behavior.
withStatuslets you test every failure branch, such as404,500, or a malformed body, without any real service producing them. - Unmet expectations.
server.verify()fails the test if an expected call never happened. Without it, a client that makes no request at all would pass a test that only checks the return value.
Use @RestClientTest for client code only. It scans for the component you name, so a controller or repository is not loaded. If the client needs another bean, add it with @Import.
Common errors
- No qualifying bean for
MockRestServiceServer. The client did not use the injected builder. Check fornew RestTemplate()or aRestTemplatebean built elsewhere. No further requests expected. The client sent a request that noexpect(...)call matched, or sent more calls than you declared. Compare the URL and method in the message with your expectation.- Unresolved placeholder
greeting.base-url. The slice does not load yourapplication.propertiesoverrides for other profiles. Set the value in thepropertiesattribute, as shown above. - Dates come out as numbers. You built an
ObjectMapperby hand. InjectJacksonTesteror the Spring-managedObjectMapperinstead. - A JSON test passes in isolation but your API fails.
@JsonTestchecks the mapper, not the endpoint. A controller can still return a different type or a wrapper. Keep one@WebMvcTestassertion on the response body as well.
Choosing between the two
Write a @JsonTest when the JSON is a public contract: an API consumed by other teams, a message on a queue, or a stored document. Write a @RestClientTest for every class that calls an outside HTTP service. The two tests share a payload format, so reuse sample JSON files in src/test/resources and read them in both. Neither test replaces a few full-stack tests, but both run in well under a second once the context is cached.
Exercise
A teammate changes the Greeting record component issuedOn to issued. All service and controller tests that mock GreetingService still pass. Which test from this chapter fails first, and why? What does the client test need so that it also catches the change?
Show answer
The @JsonTest fails. The serialization test looks for $.issuedOn, which no longer exists, and the deserialization test now maps an unknown or missing field. Controller tests with a mocked service never assert on the JSON field names. The @RestClientTest already catches the change if its canned response is realistic and its assertion compares the whole Greeting: the response still contains issuedOn, so issued would be null and the equality check would fail. A client test that only checks name would miss it, so assert on the full object.
Exercise
Why must a client class receive RestTemplateBuilder through its constructor to work with @RestClientTest, and what does server.verify() add to a test?
Show answer
@RestClientTest registers a customizer on RestTemplateBuilder that routes every template it builds to MockRestServiceServer. A template created with new RestTemplate() skips that customizer and tries a real connection. server.verify() fails the test if a declared expectation was never met, which catches a client that never sends the request.