简体   繁体   English

如何使用有条件地返回响应的Spring REST Docs来记录REST服务?

[英]How to document REST services with Spring REST Docs that return a response conditionally?

I've a REST service that has an access limit per resource. 我有一个REST服务,每个资源都有一个访问限制。 Let's say that I've the following service: 假设我有以下服务:

GET /record/{recordId} GET / record / {recordId}

An access count per record is defined and when the limit is reached, it returns an exception. 定义每个记录的访问计数,当达到限制时,它返回一个异常。

I wrote an integration test that creates the record with an access limit of 5 and then creates a loop which sends requests via mockMvc. 我编写了一个集成测试,创建访问限制为5的记录,然后创建一个通过mockMvc发送请求的循环。

When I look at the examples in Spring REST Docs, I see that .andDo(...) is added right after the test which creates the snippets for the test. 当我查看Spring REST Docs中的示例时,我发现在测试之后添加了.andDo(...),它为测试创建了片段。 I'm afraid that it'd overwrite the same test's snippets. 我担心它会覆盖同一个测试的片段。 I want to document that the resource has access limits per resourceId and provide an example when the resource is accessible and when the access limit is reached. 我想记录资源是否具有每个resourceId的访问限制,并在资源可访问和达到访问限制时提供示例。

Should I use 2 document ID's for these cases (see below)? 我是否应该为这些案件使用2个文件ID(见下文)? Is this the right approach? 这是正确的方法吗?

@Test
public void testWithLimit(final String recordId, final String value, final int limit) throws Exception {
    for (int i = 0; i < limit; i++) {
        final ResultActions test = mockMvc.perform(get("/record/" + recordId));

        if (i < limit) {
            test.andExpect(status().isFound())
                .andExpect(jsonValue("$.value").exists())
                .andDo(document("resource-accessible"));
        } else {
            test.andExpect(status().isGone())
                .andExpect(validateException(RecordLimitExceededException.class))
                .andDo(document("resource-access-limit-reached"));
        }
    }
}

Yes, I'd definitely use two different document IDs for these two cases so that you get a set of snippets for both. 是的,对于这两种情况,我肯定会使用两种不同的文档ID,这样您就可以获得一组代码片段。

It's not necessary, but you may also want to consider only calling document twice in the loop: once for the first call that will succeed and then once for the final call when you expect the limit to have been reached. 这没有必要,但您可能还想考虑仅在循环中调用文档两次:一次是第一次调用将成功,然后一次调用最终调用,当您预期达到限制时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM