Spring RestDocs - 子文档中的文档链接?

Spring RestDocs - document links in child documents?

如何使用 Spring REST Docs 记录子文档中的链接?

给定以下 JSON 文档:

{
  "links": {
    "alpha": "http://example.com/alpha",
    "beta": "http://example.com/beta"
  }
}

我可以通过实施自定义 LinkExtractor as suggested in the reference docs (I have working implementation that is very similar to the HalLinkExtractor):

来记录 links
mockMvc.perform(get("/"))
    .andDo(document("root-resource",
        links(customLinkExtractor(),
            linkWithRel("alpha").description("Link to the Alpha resource"),
            linkWithRel("beta").description("Link to the Beta resource")
        )
    ));

但是,我的 JSON 文档在其他地方包含 links 个子文档,例如

{
    "links": {
        "alpha": "http://example.com/alpha",
        "beta": "http://example.com/beta",
    },
    "foo": {
        "links": {
            "gamma": "https://gamma.com/",
            "delta": "https://delta.com/"
        }
    }
}

如何记录与 foo 子文档关联的 links 文档?理想情况下,我想做类似的事情:

mockMvc.perform(get("/"))
    .andDo(document("root-resource",
        links(customLinkExtractor(),
            linkWithRel("alpha").description("Link to the Alpha resource"),
            linkWithRel("beta").description("Link to the Beta resource")
        ),
        links(jsonPath("$.foo"), 
            customLinkExtractor(),
            linkWithRel("gamma").description("Link to the Gamma resource"),
            linkWithRel("delta").description("Link to the Delta resource")
        )
    ));

当然,这行不通,因为没有 jsonPath(..) 方法。还有哪些其他选项可用?

我想如果您使用 HalLinkExtractor 并尝试在 _embedded 子文档中记录链接(请参阅 draft-kelly-json-hal 中的示例),也会出现同样的问题。

我认为您使用自定义 link 提取器是在正确的轨道上。与其尝试使用单独的 jsonPath 方法,不如将该功能添加到自定义提取器中?然后您可以告诉它在哪里寻找 links。例如:

mockMvc.perform(get("/"))
    .andDo(document("root-resource",
        links(customLinkExtractor("$.links", "$.foo.links"),
            linkWithRel("alpha").description("Link to the Alpha resource"),
            linkWithRel("beta").description("Link to the Beta resource"),
            linkWithRel("gamma").description("Link to the Gamma resource"),
            linkWithRel("delta").description("Link to the Delta resource")
        )
    ));