使用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>

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>

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")
                        )
                        )
                );
    }

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");
    }

5 .运行maven package命令时,插件会将adoc文件转化成html文件,变为离线文档,代码地址


结束

附上单元测试图片一张:
这里写图片描述

 

posted @ 2017-08-14 17:20  alvis_u  阅读(642)  评论(0编辑  收藏  举报