SKILL.md--- name: unit-test-json-serialization description: Provides patterns for unit testing JSON serialization/deserialization with Jackson and `@JsonTest`. Validates JSON mapping, custom serializers, date formats, and polymorphic types. Use when testing JSON serialization, validating custom serializers, or writing JSON unit tests in Spring Boot applications. allowed-tools: Read, Write, Bash, Glob, Grep --- # Unit Testing JSON Serialization with `@JsonTest` ## Overview Provides patterns for unit testing JSON serialization and deserialization using Spring's `@JsonTest` and Jackson. Covers POJO mapping, custom serializers, field name mappings, nested objects, date/time formatting, and polymorphic types. ## When to Use - Testing JSON serialization/deserialization of DTOs - Verifying custom Jackson serializers/deserializers - Validating `@JsonProperty`, `@JsonIgnore`, and field name mappings - Testing date/time format handling (LocalDateTime, Date) - Testing null handling and missing fields - Testing polymorphic type deserialization ## Instructions 1. **Annotate test class with `@JsonTest`** → Enables JacksonTester auto-configuration 2. **Autowire JacksonTester for target type** → Provides type-safe JSON assertions 3. **Test serialization** → Call `json.write(object)` and assert JSON paths with `extractingJsonPath*` 4. **Test deserialization** → Call `json.parse(json)` or `json.parseObject(json)` and assert object state 5. **Validate round-trip** → Serialize, then deserialize, verify same data (if object is properly comparable) 6. **Test edge cases** → Null values, missing fields, empty collections, invalid JSON 7. **Add validation checkpoints**: After each assertion, verify the test fails meaningfully with wrong data ## Examples ### Maven Setup ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> ``` ### Gradle Setup ```kotlin dependencies { implementation("org.springframework.boot:spring-boot-starter-json") testImplementation("org.springframework.boot:spring-boot-starter-test") } ``` ### Basic Serialization and Deserialization ```java @JsonTest class UserDtoJsonTest { @Autowired private JacksonTester<UserDto> json; @Test void shouldSerializeUserToJson() throws Exception { UserDto user = new UserDto(1L, "Alice", "alice@example.com", 25); JsonContent<UserDto> result = json.write(user); result .extractingJsonPathNumberValue("$.id").isEqualTo(1) .extractingJsonPathStringValue("$.name").isEqualTo("Alice") .extractingJsonPathStringValue("$.email").isEqualTo("alice@example.com") .extractingJsonPathNumberValue("$.age").isEqualTo(25); } @Test void shouldDeserializeJsonToUser() throws Exception { String json_content = "{\"id\":1,\"name\":\"Alice\",\"ema