使用spring-restdocs 自動生成接口文檔

前言

Spring REST Docs helps you to document RESTful services. It combines hand-written documentation written with Asciidoctor and auto-generated snippets produced with Spring MVC Test. This approach frees you from the limitations of the documentation produced by tools like Swagger. It helps you to produce documentation that is accurate, concise, and well-structured. This documentation then allows your users to get the information they need with a minimum of fuss. [ Spring百科 ]html

開始

1 .官網地址-下載地址,在pom.xml文件中添加以下配置:java

<dependencies>
    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <version>1.2.1.RELEASE</version>
    </dependency>
</dependencies>

2 .在插件中添加以下配置,當使用maven命令是會自動將單元測試裏的請求編譯成assicdoc文件:python

<plugin>
      <groupId>org.asciidoctor</groupId>
      <artifactId>asciidoctor-maven-plugin</artifactId>
      <version>1.5.5</version>
      <executions>
          <execution>
              <id>generate-docs</id>
              <phase>prepare-package</phase>
              <goals>
                  <goal>process-asciidoc</goal>
              </goals>
              <configuration>
                  <backend>html</backend>
                  <doctype>book</doctype>
                  <attributes>
                      <snippets>${project.build.directory}/generated-snippets</snippets>
                  </attributes>
                  <sourceDirectory>src/docs/api/asciidocs</sourceDirectory>
                  <outputDirectory>src/docs/api/html</outputDirectory>
              </configuration>
          </execution>
      </executions>
      <dependencies>
          <dependency>
              <groupId>org.springframework.restdocs</groupId>
              <artifactId>spring-restdocs-asciidoctor</artifactId>
              <version>${spring-restdoc-version}</version>
          </dependency>
      </dependencies>
  </plugin>

3 .對rest api進行單元測試和文檔描述,代碼以下git

@Test
    public void GetAllUserTest() throws Exception {

        this.mockMvc
                .perform(
                        post("/api/webchart/list")
                                .header("access_token", "2E14D92B-1FB1-4D04-8EA3-486DA78914BA")
                                .header("user_uuid", "05d44c79-627b-466c-940a-c62074107226")
                                .param("age", "1")
                )
                .andExpect(status().isOk())
                .andDo(document("1.1 獲取全部用戶接口",
                        preprocessRequest(prettyPrint()),
                        preprocessResponse(prettyPrint()),
                        requestHeaders(
                                headerWithName("access_token").description("Basic auth credentials"),
                                headerWithName("user_uuid").description("User Uuid Key")
                        ),
                        requestParameters(
                                parameterWithName("age").description("年齡")
                        ),
                        responseFields(
                                fieldWithPath("code").description("0.失敗 1.成功").type(JsonFieldType.NUMBER),
                                fieldWithPath("message").description("提示消息"),
                                fieldWithPath("userList[].id").description("用戶id"),
                                fieldWithPath("userList[].name").description("姓名"),
                                fieldWithPath("userList[].age").description("用戶密碼"),
                                fieldWithPath("userList[].lastActiveTime").description("最近活動時間"),
                                fieldWithPath("userList[].user_name").description("用戶名"),
                                fieldWithPath("userList[].password").description("用戶密碼"),
                                fieldWithPath("userList[].uuid").description("用戶UUId")
                        )
                        )
                );
    }

4 .將全部adoc文檔組裝在一塊兒github

@Test
    public void adocBuild() throws IOException {
        String appDir = System.getProperty("user.dir");
        String adocPath = appDir + "/src/docs/api/asciidocs/apiList.adoc";
        StringBuilder content = new StringBuilder();
        content.append("include::" + appDir + "/src/docs/api/asciidocs/preview.adoc");

        File apidirs = new File(appDir + "/target/generated-snippets");
        for (File apidir : apidirs.listFiles()) {
            String apiName = apidir.getName();
            content.append("=== " + apiName + "\n\n");
            fileAppend(content, apidir + "/request-headers.adoc", "request-headers 類型說明");
            fileAppend(content, apidir + "/http-request.adoc", "http-request");
            fileAppend(content, apidir + "/request-parameters.adoc", "request-parameters類型說明");
            fileAppend(content, apidir + "/request-body.adoc", "request-body類型說明");
            fileAppend(content, apidir + "/http-response.adoc", "http-response");
            fileAppend(content, apidir + "/response-fields.adoc", "response-fields 類型說明");
        }
        File file = new File(adocPath);
        FileUtils.writeStringToFile(file, content.toString(), "utf-8");
    }

5 .運行maven package命令時,插件會將adoc文件轉化成html文件,變爲離線文檔,代碼地址web


結束

附上單元測試圖片一張:
這裏寫圖片描述spring

相關文章
相關標籤/搜索