Sub topic 11
Testing Record DTOs with @JsonTest
This chapter covers how to test the JSON shape of record DTOs, and how to test their validation rules, without starting the whole application. It assumes you know Java 17 records, a basic Spring Boot REST controller, JSON and HTTP bodies, and the earlier chapters on Jackson binding and Bean Validation.
Why test DTOs at all
A record DTO looks too simple to break. Its behavior is still part of your public API contract:
- A renamed record component changes a JSON field name, which breaks clients.
- A missing or misplaced constraint lets bad data reach the service layer.
- A compact constructor that normalizes input can have bugs, such as failing on
null. - A Jackson annotation such as
@JsonPropertyor@JsonIgnorecan silently stop applying after a refactor.
Testing the DTOs directly catches these problems in milliseconds. You don't need a database, a web server, or a full @SpringBootTest.
What @JsonTest does
@JsonTest is a Spring Boot test slice. It starts a small application context that contains only JSON-related beans:
- The Jackson
ObjectMapper, configured the way Spring Boot configures it, including yourapplication.propertiessettings and anyModuleor@JsonComponentbeans. JacksonTester,JsonbTesterandGsonTesterhelpers, depending on which library is on the classpath.
It does not load controllers, services, repositories or a database. Because the ObjectMapper is the same one your application uses, the test sees the same serialization rules as production. Creating new ObjectMapper() by hand would miss Spring Boot's defaults, such as the registered Java time module.
Testing serialization
Serialization is the step where your Java object becomes JSON. The JacksonTester<T> wraps the ObjectMapper for type T. Its write method returns a JsonContent, and AssertJ assertions on it let you check the output.
This is the response record from earlier chapters, with a test for it:
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");
}
}The expression $.name is a JsonPath. $ is the root of the document, and .name selects the field. The extractingJsonPath... methods exist for several types:
| Method | Use it for |
|---|---|
| `extractingJsonPathStringValue` | String fields |
| `extractingJsonPathNumberValue` | Numeric fields |
| `extractingJsonPathBooleanValue` | Boolean fields |
| `extractingJsonPathArrayValue` | Arrays |
| `hasJsonPathStringValue` | Checking that a path exists and holds a string |
| `doesNotHaveJsonPath` | Checking that a field is absent |
Checking the whole document
Checking one field at a time is precise, but it can miss extra fields. To pin down the entire output, compare it with an expected JSON string:
@Test
void producesExactJson() throws Exception {
UserResponse response = new UserResponse(1L, "Ada", "[email protected]");
assertThat(json.write(response)).isEqualToJson("""
{"id": 1, "name": "Ada", "email": "[email protected]"}
""");
}isEqualToJson compares in lenient mode by default. Lenient mode ignores field order and allows extra fields in the actual output. That is why it can pass even when the record gains an unexpected field. For strict comparison, pass a JSONCompareMode:
import org.skyscreamer.jsonassert.JSONCompareMode;
assertThat(json.write(response)).isEqualToJson("""
{"id": 1, "name": "Ada", "email": "[email protected]"}
""", JSONCompareMode.STRICT);Strict mode fails if there are extra fields or array order differs. It still ignores the order of object fields. Use strict mode when the test exists to protect an API contract.
Testing a hidden field
If a record has a field that must never appear in output, assert its absence. Suppose a record uses @JsonIgnore on a component:
import com.fasterxml.jackson.annotation.JsonIgnore;
public record AccountResponse(Long id, String owner, @JsonIgnore String internalNote) {
}@JsonTest
class AccountResponseJsonTest {
@Autowired
private JacksonTester<AccountResponse> json;
@Test
void hidesInternalNote() throws Exception {
AccountResponse response = new AccountResponse(7L, "Ada", "do not expose");
assertThat(json.write(response)).doesNotHaveJsonPath("$.internalNote");
}
}This kind of test guards against a data leak. If someone removes the annotation later, the test fails.
Testing deserialization
Deserialization turns incoming JSON into a record. This is what happens to a request body before your controller method runs. Jackson uses the record's canonical constructor, so the compact constructor runs during this step too.
JacksonTester provides parse for a JSON string and parseObject for the resulting object:
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 NormalizedRequestJsonTest {
record NormalizedRequest(String name, String email) {
NormalizedRequest {
name = name == null ? null : name.strip();
email = email == null ? null : email.strip().toLowerCase();
}
}
@Autowired
private JacksonTester<NormalizedRequest> json;
@Test
void normalizesInputWhileReading() throws Exception {
String content = """
{"name": " Ada ", "email": " [email protected] "}
""";
NormalizedRequest request = json.parseObject(content);
assertThat(request.name()).isEqualTo("Ada");
assertThat(request.email()).isEqualTo("[email protected]");
}
@Test
void acceptsMissingFields() throws Exception {
NormalizedRequest request = json.parseObject("{}");
assertThat(request.name()).isNull();
assertThat(request.email()).isNull();
}
}The nested record keeps the example self-contained. In a real project you would test your own CreateUserRequest in the same way. The second test is worth copying. Missing JSON fields become null for reference types and the default value for primitives (for example 0 for an int). A compact constructor that calls name.strip() without a null check would throw on this input, and this test would catch that.
The primitive trap
The CreateUserRequest from the validation chapter declares @Min(18) int age. If the client omits age, Jackson does not fail by default. It passes 0 to the constructor. Validation then reports "must be greater than or equal to 18", which is a misleading message for a missing field. A test documents this behavior:
@Test
void missingPrimitiveBecomesZero() throws Exception {
CreateUserRequest request = json.parseObject("""
{"name": "Ada", "email": "[email protected]"}
""");
assertThat(request.age()).isZero();
}If you want the absence to be distinguishable, declare the component as Integer with @NotNull. A test like the one above then asserts isNull() instead, and you will see that change immediately.
Testing rejected input
Some bad input should fail during parsing. The compact constructor may throw, or the JSON may have the wrong type. Jackson wraps the failure, so assert on the exception type and, where useful, the cause:
import com.fasterxml.jackson.databind.JsonMappingException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
void rejectsWrongType() {
assertThatThrownBy(() -> json.parseObject("""
{"id": "not-a-number", "name": "Ada", "email": "[email protected]"}
"""))
.isInstanceOf(JsonMappingException.class);
}The exact exception class depends on the Jackson version and the kind of failure. JsonMappingException is the common parent for binding problems, so it is the safest class to assert against. Don't assert on the full message text, because it changes between Jackson releases.
Round trips
A round trip serializes an object and parses the result. The new object should equal the original. Records generate equals from their components, so the comparison needs no extra code:
@Test
void roundTrips() throws Exception {
UserResponse original = new UserResponse(1L, "Ada", "[email protected]");
String text = json.write(original).getJson();
UserResponse copy = json.parseObject(text);
assertThat(copy).isEqualTo(original);
}A round trip does not replace field-level assertions. If you rename a component in both directions, such as with a consistent @JsonProperty, the round trip still passes while the contract has changed. Keep at least one test that checks the literal field names.
Testing Jackson annotations
If a record uses @JsonProperty to rename a field or @JsonInclude to drop nulls, test that effect directly:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
public record ProfileResponse(
@JsonProperty("full_name") String fullName,
@JsonInclude(JsonInclude.Include.NON_NULL) String nickname) {
}@JsonTest
class ProfileResponseJsonTest {
@Autowired
private JacksonTester<ProfileResponse> json;
@Test
void usesSnakeCaseName() throws Exception {
ProfileResponse response = new ProfileResponse("Ada Lovelace", null);
assertThat(json.write(response)).hasJsonPathStringValue("$.full_name");
assertThat(json.write(response)).doesNotHaveJsonPath("$.nickname");
}
@Test
void readsSnakeCaseName() throws Exception {
ProfileResponse response = json.parseObject("""
{"full_name": "Ada Lovelace"}
""");
assertThat(response.fullName()).isEqualTo("Ada Lovelace");
assertThat(response.nickname()).isNull();
}
}Testing Bean Validation without Spring
@JsonTest does not check constraint annotations. Validation is a separate step, normally triggered by @Valid in the controller. You can test the constraints on a record without any Spring context by using the Jakarta Validator directly:
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.Set;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class CreateUserRequestValidationTest {
record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@Min(18) int age) {
}
private static ValidatorFactory factory;
private static Validator validator;
@BeforeAll
static void setUp() {
factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@AfterAll
static void tearDown() {
factory.close();
}
@Test
void validRequestHasNoViolations() {
var request = new CreateUserRequest("Ada", "[email protected]", 36);
assertThat(validator.validate(request)).isEmpty();
}
@Test
void reportsEachBrokenComponent() {
var request = new CreateUserRequest(" ", "not-an-email", 12);
Set<ConstraintViolation<CreateUserRequest>> violations = validator.validate(request);
assertThat(violations)
.extracting(v -> v.getPropertyPath().toString())
.containsExactlyInAnyOrder("name", "email", "age");
}
}The property path for a record component is the component name, so you can assert on "name", "email" and "age". This test needs a Bean Validation provider on the classpath. spring-boot-starter-validation brings in Hibernate Validator.
Choosing the right test type
| Question | Test with |
|---|---|
| Does the record produce the right JSON? | `@JsonTest` and `write` |
| Does JSON become the right record, including normalization? | `@JsonTest` and `parseObject` |
| Do the constraints reject bad values? | Jakarta `Validator` in a plain unit test |
| Does a bad request return HTTP 400? | A controller slice test, covered in the web layer testing material |
Common errors
No qualifying bean of type JacksonTester. The test class is missing@JsonTest, orspring-boot-starter-testis not a test dependency.- Tests pass but production output differs. The test built its own
ObjectMapper. InjectJacksonTesterinstead so the configured mapper is used. isEqualToJsonpasses with extra fields. Lenient mode is the default. UseJSONCompareMode.STRICTwhen you need exactness.- Validation is never triggered.
@JsonTestdoes not run theValidator. Call it explicitly, as shown above. - Parsing fails on a record with a private or package-private constructor. The canonical constructor of a record has the same access as the record. Keep records that Jackson must read accessible.
Summary of what to test
For each DTO, a useful minimum is:
- One serialization test that checks the field names and values clients rely on.
- One deserialization test with a realistic payload.
- One test for missing fields, to confirm
nulland default handling. - One test for each compact constructor rule.
- One validation test that triggers every constraint at least once.
Exercise
A record PriceResponse(String currency, @JsonIgnore String costBasis) is returned by an endpoint. Write the assertion, using a JacksonTester<PriceResponse> named json, that proves costBasis never appears in the output. Why is isEqualToJson in its default mode a weak way to check this?
Show answer
assertThat(json.write(new PriceResponse("EUR", "secret"))).doesNotHaveJsonPath("$.costBasis");. The default mode of isEqualToJson is lenient, so it allows extra fields in the actual output. A leaked costBasis field would not make the comparison fail. doesNotHaveJsonPath, or JSONCompareMode.STRICT, catches it.
Exercise
A client sends {"name": "Ada", "email": "[email protected]"} to an endpoint whose request record declares @Min(18) int age. What value does age have after Jackson parses the body, and how would you change the record so a missing age can be told apart from an age of 0?
Show answer
By default age is 0, because Jackson supplies the default value for a missing primitive component. Change the component to Integer age and add @NotNull, with @Min(18) kept. A missing value then arrives as null and fails @NotNull, which is a clearer error than a minimum-value violation.