【问题标题】:How to document recursive data structures in response with Spring REST Docs如何记录递归数据结构以响应 Spring REST Docs
【发布时间】:2020-01-31 04:40:45
【问题描述】:

我有一个关于 Spring Restdocs 的问题。我要记录的其余调用之一返回一个递归数据结构,具有不同类型的子节点:叶子和子树。叶和子树具有不同的属性。例如:

{
    "id": "$",
    "left": {
        "id": "l",
        "left": {
            "id": "l1",
            "type": "leaf",
            "value": "Leaf 1"
        },
        "right": {
            "id": "l2",
            "type": "leaf",
            "value": "Leaf 2"
        },
        "type": "subtree"
    },
    "right": {
        "id": "l3",
        "type": "leaf",
        "value": "Leaf 3"
    },
    "type": "subtree"
}

我找不到如何使用 Spring Restdocs 记录这些递归数据结构。 有没有人有一些例子或可以帮助我。

我已经设置了一个 git repo,其中包含一些显示我的问题的代码: https://github.com/dibog/spring-restdocs-recursive-demo

最好的问候, 迪特

【问题讨论】:

    标签: spring-restdocs


    【解决方案1】:

    这完全取决于您要记录的内容以及您希望如何向用户描述事物。我会关注两种不同类型的节点——子树和叶子——并提供描述它们的格式的文档,并且树中的每个节点要么是叶子,要么是子树。

    您可以使用 REST Docs 使用响应字段 sn-p 记录两种不同节点类型的结构,重点关注响应的特定部分:

    responseFields(beneathPath("left.left").withSubsectionId("leaf"),
        fieldWithPath("id").description("ID of the node"),
        fieldWithPath("type").description("Type of the node. Always 'leaf' for leaf nodes"),
        fieldWithPath("value").description("Value of the node")),
    responseFields(beneathPath("left").withSubsectionId("subtree"),
        fieldWithPath("id").description("ID of the node"),
        fieldWithPath("type").description("Type of the node. Always 'subtree' for nodes with children"),
        subsectionWithPath("left").description("Left-hand child node. Either a subtree or a leaf"),
        subsectionWithPath("right").description("Right-hand child node. Either a subtree or a leaf"))
    

    在记录子树节点时使用subsectionWithPath 允许您使用单个描述符覆盖整个子树。该描述告知用户leftright 的值将是一个节点,它可以是叶节点,也可以是另一个子树。

    【讨论】:

    • 嗨,安迪,感谢您的解释和代码示例。我想我大致了解你的小费。您记录单独的节点。但我不确定如何将您的片段添加到测试用例中。我尝试将它们添加到我的测试用例中,但失败并显示与以前完全相同的错误消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多