Video in progress
What is @JsonTest for, and what bugs does testing JSON serialization separately catch?
@JsonTest starts only the Jackson layer: the ObjectMapper configured by Boot, the @JsonComponents and the modules. That way you can quickly check how date formats, null fields, BigDecimal and enum names will come out in prod, without a controller or a database.
📖 Answer
Many teams create new ObjectMapper() in a unit test and check the DTO with it. That's a different mapper: Boot turns off WRITE_DATES_AS_TIMESTAMPS and FAIL_ON_UNKNOWN_PROPERTIES in its own, registers JavaTimeModule and applies the spring.jackson.* properties. As a result the JSON in the test doesn't look like the JSON in prod.
@JsonTest
class CourseResponseJsonTest {
@Autowired JacksonTester<CourseResponse> json;
@Test
void serializesAsClientExpects() throws Exception {
var dto = new CourseResponse(7L, "Java Core", new BigDecimal("250000.00"),
LocalDate.of(2026, 3, 1), null);
var content = json.write(dto);
assertThat(content).extractingJsonPathStringValue("$.publishedAt").isEqualTo("2026-03-01");
assertThat(content).extractingJsonPathNumberValue("$.price").isEqualTo(250000.00);
assertThat(content).doesNotHaveJsonPath("$.discount"); // NON_NULL policy
}
@Test
void ignoresUnknownFieldsFromOldClients() throws Exception {
assertThat(json.parseObject("{\"id\":7,\"title\":\"Java\",\"legacy\":1}").title())
.isEqualTo("Java");
}
}
Real bugs a test like this catches: someone swapped LocalDateTime for Instant and the front end got "2026-03-01T00:00:00Z" and showed the date shifted by a day; a record component got renamed and the JSON field name silently changed with it; @JsonValue was added to an enum.
The test is fast, because the Spring context is tiny. I make such tests mandatory for the main DTOs of the public API: JSON is a contract, and the Java class is only one view of it.
Sign up to mark studied questions and save your progress.