Token导航 LogoToken导航TokenDH.com
开发只读github未标认证来源可访问许可证需确认审计通过

unit-test-json-serializationunit 测试 JSON serialization

Agent Skill

用于辅助测试设计、自动化测试、用例整理和回归验证。它适合让 Agent 编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

总安装

494

周安装

20

GitHub Stars

217

下载量

155
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:unit-test-json-serialization(unit 测试 JSON serialization)
来源仓库:https://github.com/giuseppe-trisciuoglio/developer-kit-claude-code
仓库路径:skills/unit-test-json-serialization
安装命令:
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit-claude-code --skill unit-test-json-serialization
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit-claude-code --skill unit-test-json-serialization

简介

用于辅助 JSON 序列化与反序列化的单元测试覆盖。

  • 适合验证对象转换、嵌套结构与日期格式兼容性。
  • 使用时需确认 Jackson 或 Gson 配置与注解设置。
  • 应包含 null 值、循环引用等边缘情况的处理测试。
  • unit-test-json-serialization 属于开发类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

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

<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

dependencies {
  implementation("org.springframework.boot:spring-boot-starter-json")
  testImplementation("org.springframework.boot:spring-boot-starter-test")
}

Basic Serialization and Deserialization

@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\",\"email\":\"alice@example.com\",\"age\":25}";
    UserDto user = json.parse(json_content).getObject();

    assertThat(user.getId()).isEqualTo(1L);
    assertThat(user.getName()).isEqualTo("Alice");
    assertThat(user.getEmail()).isEqualTo("alice@example.com");
    assertThat(user.getAge()).isEqualTo(25);
  }

  @Test
  void shouldHandleNullFields() throws Exception {
    String json_content = "{\"id\":1,\"name\":null,\"email\":\"alice@example.com\"}";
    UserDto user = json.parse(json_content).getObject();
    assertThat(user.getName()).isNull();
  }
}

Custom JSON Properties

public class Order {
  @JsonProperty("order_id")
  private Long id;

  @JsonProperty("total_amount")
  private BigDecimal amount;

  @JsonIgnore
  private String internalNote;
}

@JsonTest
class OrderJsonTest {

  @Autowired
  private JacksonTester<Order> json;

  @Test
  void shouldMapJsonPropertyNames() throws Exception {
    String json_content = "{\"order_id\":123,\"total_amount\":99.99}";
    Order order = json.parse(json_content).getObject();
    assertThat(order.getId()).isEqualTo(123L);
    assertThat(order.getAmount()).isEqualByComparingTo(new BigDecimal("99.99"));
  }

  @Test
  void shouldIgnoreJsonIgnoreFields() throws Exception {
    Order order = new Order(123L, new BigDecimal("99.99"));
    order.setInternalNote("Secret");
    assertThat(json.write(order).json).doesNotContain("internalNote");
  }
}

Nested Objects

public class Product {
  private Long id;
  private String name;
  private Category category;
  private List<Review> reviews;
}

@JsonTest
class ProductJsonTest {

  @Autowired
  private JacksonTester<Product> json;

  @Test
  void shouldSerializeNestedObjects() throws Exception {
    Product product = new Product(1L, "Laptop", new Category(1L, "Electronics"));
    JsonContent<Product> result = json.write(product);

    result
      .extractingJsonPathNumberValue("$.category.id").isEqualTo(1)
      .extractingJsonPathStringValue("$.category.name").isEqualTo("Electronics");
  }

  @Test
  void shouldDeserializeNestedObjects() throws Exception {
    String json_content = "{\"id\":1,\"name\":\"Laptop\",\"category\":{\"id\":1,\"name\":\"Electronics\"}}";
    Product product = json.parse(json_content).getObject();
    assertThat(product.getCategory().getName()).isEqualTo("Electronics");
  }

  @Test
  void shouldHandleListOfNestedObjects() throws Exception {
    String json_content = "{\"id\":1,\"reviews\":[{\"rating\":5},{\"rating\":4}]}";
    Product product = json.parse(json_content).getObject();
    assertThat(product.getReviews()).hasSize(2);
  }
}

Date/Time Formatting

@JsonTest
class DateTimeJsonTest {

  @Autowired
  private JacksonTester<Event> json;

  @Test
  void shouldFormatDateTimeCorrectly() throws Exception {
    LocalDateTime dt = LocalDateTime.of(2024, 1, 15, 10, 30, 0);
    json.write(new Event("Conference", dt))
      .extractingJsonPathStringValue("$.scheduledAt").isEqualTo("2024-01-15T10:30:00");
  }
}

Custom Serializers

public class CustomMoneySerializer extends JsonSerializer<BigDecimal> {
  @Override
  public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    gen.writeString(value == null ? null : String.format("$%.2f", value));
  }
}

@JsonTest
class CustomSerializerTest {

  @Autowired
  private JacksonTester<Price> json;

  @Test
  void shouldUseCustomSerializer() throws Exception {
    json.write(new Price(new BigDecimal("99.99")))
      .extractingJsonPathStringValue("$.amount").isEqualTo("$99.99");
  }
}

Polymorphic Deserialization

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
  @JsonSubTypes.Type(value = CreditCard.class, name = "credit_card"),
  @JsonSubTypes.Type(value = PayPal.class, name = "paypal")
})
public abstract class PaymentMethod { }

@JsonTest
class PolymorphicJsonTest {

  @Autowired
  private JacksonTester<PaymentMethod> json;

  @Test
  void shouldDeserializeCreditCard() throws Exception {
    String json_content = "{\"type\":\"credit_card\",\"id\":\"card123\"}";
    assertThat(json.parse(json_content).getObject()).isInstanceOf(CreditCard.class);
  }

  @Test
  void shouldDeserializePayPal() throws Exception {
    String json_content = "{\"type\":\"paypal\",\"id\":\"pp123\"}";
    assertThat(json.parse(json_content).getObject()).isInstanceOf(PayPal.class);
  }
}

Best Practices

  • Test serialization AND deserialization for complete coverage
  • Verify JSON paths individually rather than comparing full JSON strings
  • Test null handling explicitly — null fields may be included or excluded depending on @JsonInclude
  • Use extractingJsonPath* methods for precise field assertions
  • Test round-trip: serialize an object, deserialize the JSON, verify the result matches
  • Validate edge cases: empty strings, empty collections, deeply nested structures
  • Group related assertions in a single test for clarity

Constraints and Warnings

  • @JsonTest loads limited context: Only JSON-related beans; use @SpringBootTest for full Spring context
  • Jackson version: Ensure annotation versions match the Jackson version in use
  • Date formats: ISO-8601 is default; use @JsonFormat for custom patterns
  • Null handling: Use @JsonInclude(Include.NON_NULL) to exclude nulls from serialization
  • Circular references: Use @JsonManagedReference/@JsonBackReference to prevent infinite loops
  • Immutable objects: Use @JsonCreator + @JsonProperty for constructor-based deserialization
  • Polymorphic types: @JsonTypeInfo must correctly identify the subtype for deserialization to work

Debugging Workflow

When a JSON test fails, follow this workflow:

Failure SymptomCommon CauseHow to Verify
JsonPath assertion failsField name mismatchCheck @JsonProperty spelling matches JSON key
Null expected but got value@JsonInclude(NON_NULL) configuredVerify annotation on field/class
Deserialization returns wrong typeMissing @JsonTypeInfoAdd type info property to JSON or configure subtype mapping
Date format mismatchFormat string incorrectConfirm @JsonFormat(pattern=...) matches expected string
Missing field in output@JsonIgnore or transient modifierCheck field for @JsonIgnore or transient keyword
Nested object is nullInner JSON missing or malformedLog parsed JSON; verify inner structure matches POJO
JsonParseExceptionMalformed JSON stringValidate JSON syntax; check for unescaped characters

Validation checkpoint after fixing: Re-run the test — if it passes, write a complementary test for the opposite case (e.g., if you fixed null handling, add a test for non-null values to prevent regression).

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.64%
按下载量换算57

Claude

29.39%
按下载量换算46

Cursor

21.43%
按下载量换算33

Gemini CLI

9.68%
按下载量换算15

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills