スニペットの再利用
ドキュメント化されている API には、そのリソースのいくつかに共通するいくつかの機能があるのが一般的です。このようなリソースをドキュメント化する際の繰り返しを避けるために、共通の要素で構成された Snippet を再利用できます。
まず、共通要素を記述する Snippet を作成します。次の例は、その方法を示しています。
import org.springframework.restdocs.hypermedia.LinksSnippet;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links;
public final class CommonSnippets {
private CommonSnippets() {
}
public static final LinksSnippet pagingLinks = links(
linkWithRel("first").optional().description("The first page of results"),
linkWithRel("last").optional().description("The last page of results"),
linkWithRel("next").optional().description("The next page of results"),
linkWithRel("prev").optional().description("The previous page of results"));
}次に、このスニペットを使用して、リソース固有の記述子をさらに追加します。次の例は、その方法を示しています。
MockMvc
WebTestClient
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.restdocs.docs.howto.reusingsnippets.CommonSnippets;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class ReusingSnippets {
// Fields
private MockMvc mockMvc;
@Test
void test() throws Exception {
this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("example", CommonSnippets.pagingLinks.and((1)
linkWithRel("alpha").description("Link to the alpha resource"),
linkWithRel("bravo").description("Link to the bravo resource"))));
}
}| 1 | pagingLinks Snippet を再利用し、and を呼び出して、ドキュメント化されているリソースに固有の記述子を追加します。 |
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.restdocs.docs.howto.reusingsnippets.CommonSnippets;
import org.springframework.test.web.reactive.server.WebTestClient;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document;
public class ReusingSnippets {
// Fields
private WebTestClient webTestClient;
@Test
void test() {
this.webTestClient.get()
.uri("/")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody()
.consumeWith(document("example", CommonSnippets.pagingLinks.and((1)
linkWithRel("alpha").description("Link to the alpha resource"),
linkWithRel("bravo").description("Link to the bravo resource"))));
}
}| 1 | pagingLinks Snippet を再利用し、and を呼び出して、ドキュメント化されているリソースに固有の記述子を追加します。 |
この例の結果は、first、last、next、previous、alpha、bravo の rel 値を持つリンクがすべてドキュメント化されていることです。