使用spring-restdocs 生成接口文档

1. 介绍

Document RESTful services by combining hand-written documentation with auto-generated snippets produced with Spring MVC Test.

1.1 源码地址: https://gitee.com/Lnnnnnnn/spring-restdocs-demo.git

效果图如下


1562664782399.jpg

2. 快速开始

使用 maven 作为构建工具
使用spring boot 搭建项目

2.1 maven 仓库配置

有时出现jar下载不了的情况,指定spring 的仓库地址进行下载



        
            spring-snapshots
            Spring snapshots
            https://repo.spring.io/libs-release
            
                true
            
        
    

2.2 导入maven 依赖

添加依赖jar包


    

        
            org.springframework.restdocs
            spring-restdocs-mockmvc
            2.0.3.RELEASE
            test
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

    

插件添加到 pom.xml plugins 节点下


                org.asciidoctor
                asciidoctor-maven-plugin
                1.5.3
                
                    
                        generate-docs
                        prepare-package
                        
                            process-asciidoc
                        
                        
                            html
                        
                    
                
                
                    
                        org.springframework.restdocs
                        spring-restdocs-asciidoctor
                        2.0.3.RELEASE
                    
                
            

2.3 编写三个测试接口

 @GetMapping("/orders")
    public List orders() {
        ArrayList list = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            HashMap map = new HashMap<>();
            map.put("id", i);
            map.put("money", 10);
            list.add(map);
        }
        return list;
    }
    @GetMapping("/user")
    public Object queryUser(@RequestParam String name) {
        return Collections.singletonMap("name", name);
    }

    @PostMapping("/login")
    public Object login(@RequestBody LoginDTO loginDTO) {
        System.out.println("参数: " + loginDTO.getName());
        return Collections.singletonMap("token", UUID.randomUUID().toString());
    }


登录测试接口需要用到一个 LoginDTO 类接受请求体

public class LoginDTO {

    private String name;
    private String pwd;
    // get and set method 
}

2.4 添加单元测试

使用spring boot 的单元测试

package com.example;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.hamcrest.core.CombinableMatcher;
import org.hamcrest.core.IsNot;
import org.hamcrest.core.IsNull;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.HashMap;

import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.*;
import static org.springframework.restdocs.payload.PayloadDocumentation.*;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.requestParameters;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {

    @Rule
    public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext context;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
                .apply(documentationConfiguration(this.restDocumentation))
                .build();
    }

    @Test
    public void users() throws Exception {
        mockMvc.perform(get("/user").param("name", "ldh"))
                .andExpect(status().isOk())
                .andDo(
                        document("{ClassName}/{methodName}",
                                preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()),
                                requestParameters(parameterWithName("name").description("查询名字")),
                                responseFields(fieldWithPath("name").description("名字"))
                        )
                );
    }

    @Autowired
    private ObjectMapper objectMapper;

    @Test
    public void login() throws Exception {
        HashMap reqBody = new HashMap<>();
        reqBody.put("name", "ldh");
        reqBody.put("pwd", "ldh");

        mockMvc.perform(post("/login")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(reqBody)))
                .andExpect(jsonPath("$.token").value(CombinableMatcher
                        .both(IsNot.not(IsNull.nullValue())).and(IsNot.not("")))

                )
                .andDo(
                        document("{ClassName}/{methodName}",
                                requestFields(fieldWithPath("name").description("登录名"),
                                        fieldWithPath("pwd").description("密码")),
                                responseFields(fieldWithPath("token").description("登录token"))
                        )
                );
    }


}

上述单元测试运行完后会在 ./target/generated-snippets 生成 snippets 文件,这些文件是 接口的 http 报文信息

2.5 使用 snippets 文件编写接口文档

  1. 在使用之前需要在 main 目录下 新建 asciidoc 文件夹

  2. 在 asciidoc 目录下新建 adoc 后缀的文件,如:index.adoc

index.adoc 示例

= API
:toc: left
:toclevels: 4

[[order-it]]
== 1. 订单接口

[[order-query]]
=== 订单查询

operation::OrderTest/queryOrder[snippets='curl-request,request-fields,response-body,response-fields']

[[user-it]]
== 2.用户接口

[[user-query]]
=== 用户查询
operation::UserTest/users[snippets='curl-request,request-fields,response-body,response-fields']

[[user-login]]
=== 登录

提供用户登录

operation::UserTest/login[snippets='curl-request,request-fields,response-body,response-fields']

  1. 执行 mvn package 命令 生成 html 文档,在 /target/generated-docs/ 目录下会生成 index.html 文件

效果图如下


1562664782399.jpg

你可能感兴趣的:(使用spring-restdocs 生成接口文档)