【问题标题】:Spring RestDocs - document links in child documents?Spring RestDocs - 子文档中的文档链接?
【发布时间】:2017-06-24 05:01:45
【问题描述】:

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

给定以下 JSON 文档:

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

我可以按照reference docs 中的建议通过实现自定义LinkExtractor 来记录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/"
        }
    }
}

如何记录与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 中的示例)。

【问题讨论】:

    标签: spring-restdocs


    【解决方案1】:

    我认为您使用自定义链接提取器走在正确的轨道上。与其尝试使用单独的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")
            )
        ));
    

    【讨论】:

    • 我已经按照您的建议更新了我的实现(略有不同,customLinkExtractor() 总是需要links 文档的完整 jsonPath,例如$.links)。但是,现在的问题是我只看到生成的root-resource 中的gammadelta 链接的输出。或者,如果我删除上面 sn-p 中的第二个 links() 方法,我只会看到 alphabeta 链接并且测试通过。
    • 抱歉,我忽略了第二个 links 调用将覆盖第一个生成的 sn-p 的事实。我已经用一种方法更新了我的答案,该方法将生成一个包含所有链接的 sn-p。
    • 别担心,我现在有这个工作。这种方法的一个缺点是不再可能验证哪些链接属于$.links,哪些属于$.foo.links
    • 这很好。我打开了an issue 来探索在这方面做出一些改进
    猜你喜欢
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 2014-12-22
    • 2023-03-28
    • 1970-01-01
    • 2011-10-02
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多