话说程序员最厌恶两样货色,接手我的项目时没有任何文档,本人开发我的项目必须提供文档。

明天给大家分享一个能通过代码主动生成文档技术,Spring Rest Doc过在单元测试中额定增加 API 信息形容,从而主动生成对应的文档片段。
上面通过一个简略的例子演示下如何疾速上手的。在Spring Boot我的项目中增加maven 依赖

        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>        <dependency>            <groupId>org.springframework.restdocs</groupId>            <artifactId>spring-restdocs-mockmvc</artifactId>            <scope>test</scope>        </dependency>

在controller增加接口

    @PostMapping("/show/entity")    public Dog getDog(@RequestBody Dog dog){        return dog;    }

编写测试用例,并且输入文档。

import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;import org.springframework.http.MediaType;import org.springframework.restdocs.RestDocumentationContextProvider;import org.springframework.restdocs.RestDocumentationExtension;import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders;import org.springframework.test.context.junit.jupiter.SpringExtension;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.result.MockMvcResultMatchers;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;@WebMvcTest@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})class DogControllerTest {    private MockMvc mockMvc;    @BeforeEach    public void init(WebApplicationContext applicationContext, RestDocumentationContextProvider contextProvider){        mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext)                .apply(MockMvcRestDocumentation.documentationConfiguration(contextProvider))                .build();    }    @Test    void getDog() throws Exception {        String json = "{\"id\": 12,\"name\":\"Miki\"}";        mockMvc.perform(RestDocumentationRequestBuilders.post("/dog/show/entity")                        .content(json)                        .contentType(MediaType.APPLICATION_JSON_VALUE))                .andExpect(MockMvcResultMatchers.status().isOk()) //胜利响应                .andExpect(MockMvcResultMatchers.jsonPath("name","Miki").exists()) //后果匹配                .andDo(MockMvcRestDocumentation.document("dog",                        requestFields(PayloadDocumentation.fieldWithPath("name").description("名字"),                                PayloadDocumentation.fieldWithPath("id").description("实体id")),                        PayloadDocumentation.responseFields(                                PayloadDocumentation.fieldWithPath("name").description("名字"),                                PayloadDocumentation.fieldWithPath("id").description("实体id")                        ))); //输入文档    }}

在target目录能够看到生成文档

在target/generated-snippets/dog目录下会生成文档片段
例如curl-request.adoc 就是curl执行http命令执行参数,间接copy就能够执行了

$ curl 'http://localhost:8080/dog/show/entity' -i -X POST \    -H 'Content-Type: application/json' \    -d '{"id": 12,"name":"Miki"}'

要想生成一个残缺文档,这些文档全副合并成一个文档,还须要编写一个汇合文档。在我的项目src/main/asciidoc/目录下新增文件index.adoc

= 这是题目一:toc: left文章段落== 这是题目二.curl-requestinclude::{snippets}/dog/curl-request.adoc[].http-requestinclude::{snippets}/dog/http-request.adoc[].request-fieldsinclude::{snippets}/dog/request-fields.adoc[].response-bodyinclude::{snippets}/dog/response-body.adoc[].response-fieldsinclude::{snippets}/dog/response-fields.adoc[]

应用asciidoctor-maven-plugin 插件生成html文档

<plugin>                <groupId>org.asciidoctor</groupId>                <artifactId>asciidoctor-maven-plugin</artifactId>                <version>1.5.3</version>                <executions>                    <execution>                        <id>generate-docs</id>                        <phase>prepare-package</phase>                        <goals>                            <goal>process-asciidoc</goal>                        </goals>                        <configuration>                            <sourceDocumentName>index.adoc</sourceDocumentName>                            <backend>html</backend>                            <attributes>                                <snippets>${project.build.directory}/generated-snippets</snippets>                            </attributes>                        </configuration>                    </execution>                </executions>            </plugin>

运行mvn package命令后能够在target/generated-docs看见index.html,成果如下

Spring Rest Docs只是提供生成文档片而已,要生成一份残缺的问题,依然须要手动去编写index.adoc,援用文档片,通过组合的形式变成一个本人想要的文档。这个跟Swagger完去自动化生成的文档有很多区别的。两者在应用上也有很多不同。

生成形式:
  • Swagger: 只有在办法、实体对象增加注解申明即可,简略、不便,对代码有肯定侵入性。文档生成依赖我的项目提供服务,属于在线文档,反对离线导入文档。
  • Spring Rest Docs: 手动编写每一个http 办法的测试用例,并且还有标注每一个申请参数的含意,这些都是通过代码来实现的。对开发人员有肯定要求,工作量也有不少。必须测试通过了才会生成相应文档,这个保障了文档有效性。
应用场景;
  • Swagger: 因为文档提供必须我的项目提供http服务在一起,对网络环境有肯定要求,对接口权限不敏感。比方提供给同一个开发部门的前端开发应用。Swagger更多适宜在同一个开发小组内,要求文档提供速度较快,实时性高,根本就是写完一个http接口,就能提供相应的文档。
  • Spring Rest Docs:作为一个离线文档,比拟适宜跨部门或者跨厂商之间文档提供,像这种个别没有本地开发环境,调试不不便,很须要文档提供curl调用样例。接口的变动不会太频繁的,有着残缺测试用例笼罩。
    我个人感觉 Spring Rest Docs心中完满的API文档实现,Mock测试通过生成的文档,保障每一个文档都是可用、精确的,缩小人为交换。又能够依据本身需要,自由组合文档内容,既有严谨性、又具备肯定灵活性,奈何编写一份API文档须要更短工时,在不便、快捷上齐全不能与Swagger比拟,在日常开发API文档,大多数都是应用Swagger为主,然而如果当初还有团队应用Yapi这类手动编写API文档,我倡议应用Spring Rest Docs代替,让API更谨严。