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

时间:2015-11-12 20:28:09

标签: spring-restdocs

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

给出以下JSON文档:

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

我可以按LinkExtractor中建议的方式实施自定义reference docs来记录links(我的工作实施与HalLinkExtractor非常相似):

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/"
        }
    }
}

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

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中的示例),则会出现同样的问题。

1 个答案:

答案 0 :(得分:0)

我认为你使用自定义链接提取器走在正确的轨道上。而不是尝试使用单独的jsonPath方法,为什么不将该功能添加到自定义提取器?然后你可以告诉它在哪里寻找链接。例如:

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")
        )
    ));
相关问题