Sub topic 11
Testing record DTOs with @JsonTest
This chapter assumes you can write a Spring Boot REST controller, know the record syntax, and have seen Bean Validation annotations on record components. You need Java 17 or later and spring-boot-starter-test on the test classpath.
Why test DTOs on their own
A record DTO looks too simple to break. Even so, its JSON shape is part of your public API. A renamed component, a @JsonProperty annotation or a compact constructor can change the output without any compile error. A client that depends on $.name then fails at runtime.
@JsonTest is a Spring Boot test slice. It loads only the JSON infrastructure: the ObjectMapper, any Jackson modules, and your @JsonComponent beans. It does not start the web server, controllers, services or database. These tests run fast and use the same Jackson configuration as your application.
The slice gives you a JacksonTester<T> for each type you want to check.
Testing serialization
Serialization turns a record into JSON. Use json.write(...) and assert on the result with JSON path expressions.
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;
import static org.assertj.core.api.Assertions.assertThat;
@JsonTest
class UserResponseJsonTest {
@Autowired
private JacksonTester<UserResponse> json;
@Test
void serializesFields() throws Exception {
UserResponse response = new UserResponse(1L, "Ada", "[email protected]");
assertThat(json.write(response)).extractingJsonPathStringValue("$.name").isEqualTo("Ada");
}
}json.write(response) returns a JsonContent. The extractingJsonPath... methods read one value from it. Other useful assertions include hasJsonPathNumberValue("$.id") and doesNotHaveJsonPath("$.password"). The last one is a good guard against leaking fields you never meant to expose.
Testing deserialization
Deserialization turns JSON into a record. Use json.parse(...) for a string, or json.parseObject(...) to get the object directly.
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;
import static org.assertj.core.api.Assertions.assertThat;
@JsonTest
class CreateUserRequestJsonTest {
@Autowired
private JacksonTester<CreateUserRequest> json;
@Test
void readsJsonIntoRecord() throws Exception {
String content = """
{"name": "Ada", "email": "[email protected]", "age": 36}
""";
CreateUserRequest request = json.parseObject(content);
assertThat(request.name()).isEqualTo("Ada");
assertThat(request.email()).isEqualTo("[email protected]");
assertThat(request.age()).isEqualTo(36);
}
}Here CreateUserRequest is the record from the earlier chapter, with name, email and age. Because records have value-based equals, you can also compare a whole object:
assertThat(json.parse(content)).isEqualTo(new CreateUserRequest("Ada", "[email protected]", 36));This works for records only because the generated equals compares every component. You get this check without writing any equals method.
What the test proves
The diagram shows what @JsonTest loads and what it leaves out.
Testing compact constructor behavior
A compact constructor that normalizes input is easy to check with deserialization. Suppose CreateUserRequest strips whitespace and lowercases the email:
@Test
void normalizesEmailWhileReading() throws Exception {
String content = """
{"name": " Ada ", "email": "[email protected]", "age": 36}
""";
CreateUserRequest request = json.parseObject(content);
assertThat(request.name()).isEqualTo("Ada");
assertThat(request.email()).isEqualTo("[email protected]");
}Jackson calls the canonical constructor, so the normalization runs. The same test would also catch someone removing the constructor logic later.
Common mistakes
- Expecting validation to run.
@JsonTestdoes not validate. Bean Validation runs when Spring binds a@Valid @RequestBodyin a controller, or when you call aValidatoryourself. A malformedagestill deserializes here. Test constraints with aValidatoror a@WebMvcTestthat posts invalid JSON and expects a 400. - Testing only the happy path. Add cases for missing fields,
nullvalues and unknown properties. A missingintcomponent becomes0, and a missing object component becomesnull. Your constructor must handle both. - Forgetting the slice scope. Beans outside the JSON slice are not available. If a custom serializer is a plain
@Component, import it with@Import. A@JsonComponentis picked up automatically. - Asserting on whole JSON strings. Compare individual paths instead. Whole-string comparison breaks when field order or whitespace changes.
Exercise
A record UserResponse(Long id, String name, String email) must never include a password field in its JSON. Which JacksonTester assertion would check this, and why is @JsonTest a suitable place for it?
Show answer
Use assertThat(json.write(response)).doesNotHaveJsonPath("$.password"). @JsonTest loads the application's real Jackson configuration without starting the web layer or database, so the check is fast and reflects what clients actually receive.
Exercise
You add @Min(18) to age in CreateUserRequest and write a @JsonTest that parses {"name":"Ada","email":"[email protected]","age":5}. Does the test fail? Where would you test the constraint instead?
Show answer
The test does not fail, because @JsonTest only runs Jackson and never triggers Bean Validation. Test the constraint with a jakarta.validation.Validator in a plain unit test, or with @WebMvcTest by posting the invalid JSON to a controller method that uses @Valid and expecting a 400 response.