1. 程式人生 > >使用spring-restdocs 自動生成介面文件

使用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百科 ]

開始

1 .官網地址-下載地址,在pom.xml檔案中新增如下配置:

  <dependencies>
    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <version>1.2.1.RELEASE</version>
    </dependency>
</dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2 .在外掛中新增如下配置,當使用maven命令是會自動將單元測試裡的請求編譯成assicdoc檔案:

  <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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

3 .對rest api進行單元測試和文件描述,程式碼如下

      @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")
                        )
                        )
                );
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

4 .將所有adoc文件組裝在一起

     @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");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

5 .執行maven package命令時,外掛會將adoc檔案轉化成html檔案,變為離線文件,程式碼地址

結束

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