简体   繁体   中英

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. Let's say that I've the following service:

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.

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. 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.

Should I use 2 document ID's for these cases (see below)? 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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