返回

Spring Boot 单元测试中对 HATEOAS 对象的 hal+json 序列化实战指南

java

Spring Boot 单元测试中对 HATEOAS 对象的 hal+json 序列化

在开发 Web 应用程序时,HATEOAS(超文本作为应用程序状态引擎)是一个强大的工具,它允许应用程序向客户端提供与资源相关的链接。这有助于客户端在不依赖于硬编码 URL 的情况下与应用程序交互。Spring Boot 中的 HATEOAS 提供了对这种功能的内置支持。

然而,在 Spring Boot 单元测试中序列化 HATEOAS 对象为 hal+json 格式时,开发人员可能会遇到一些挑战。以下步骤将指导你解决这些挑战并成功实现测试:

注册 Jackson2HalModule

首先,你需要在测试类中注册 Jackson2HalModule。这将允许 ObjectMapper 识别和处理 HATEOAS 对象的序列化和反序列化:

@BeforeEach
public void setup() {
    objectMapper.registerModule(new Jackson2HalModule());
}

使用下划线格式

_links 属性的名称从 "links" 更改为 "links"(带下划线)。这是 HATEOAS 序列化所需使用的正确名称:

Item testItem = new Item("test");
testItem.add(linkTo(ItemController.class).slash(testItem.getId()).withSelfRel());
testItem.add(linkTo(methodOn(CategoryController.class).getCategoryById(testItem.getCategory().getId()))
        .withRel("category"));

设置忽略未知属性

配置 ObjectMapper 忽略未知属性,因为 HATEOAS 对象可能包含一些测试中不需要的附加属性:

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

使用 ObjectWriter

testItem 序列化为字符串时,请使用 ObjectWriter 而不是 ObjectMapper。它提供了更好的控制和格式化输出:

ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
String itemSerialized = ow.writeValueAsString(testItem);

修改后的测试代码

以下为修改后的测试代码,包含了上述更改:

@BeforeEach
public void setup() {
    objectMapper.registerModule(new Jackson2HalModule());
}

@Test
void testCreate() throws Exception {
    Item testItem = new Item("test");
    testItem.add(linkTo(ItemController.class).slash(testItem.getId()).withSelfRel());
    testItem.add(linkTo(methodOn(CategoryController.class).getCategoryById(testItem.getCategory().getId()))
            .withRel("category"));

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
    String itemSerialized = ow.writeValueAsString(testItem);

    mockMvc.perform(post("/items/")
            .content(itemSerialized)
            .contentType(MediaTypes.HAL_JSON_VALUE))
            .andExpect(status().isOK());
}

结论

通过遵循这些步骤,你应该能够在 Spring Boot 单元测试中正确序列化对象为 hal+json 格式。这将解决关系结构不一致的问题,让你能够有效地测试 HATEOAS 端点的行为。

常见问题解答

  1. 为什么需要注册 Jackson2HalModule?

    • 注册 Jackson2HalModule 允许 ObjectMapper 识别和处理 HATEOAS 对象的序列化和反序列化。
  2. 为什么需要使用下划线格式?

    • HATEOAS 序列化要求将 _links 属性的名称从 "links" 更改为 "links"(带下划线)。
  3. 何时应该设置忽略未知属性?

    • 忽略未知属性的设置是可选的。如果 HATEOAS 对象包含测试中不需要的附加属性,则可以设置此项。
  4. 何时应该使用 ObjectWriter?

    • 序列化 testItem 时,使用 ObjectWriter 可以提供更好的控制和格式化输出。
  5. 如何处理 Spring Boot 中 HATEOAS 单元测试中的其他潜在问题?

    • 如果遇到其他问题,请参考 Spring Boot 文档或在线社区,以获取更多帮助和解决方案。