关于spring:Spring-Rest-Docs使用

11次阅读

共计 4394 个字符,预计需要花费 11 分钟才能阅读完成。

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

明天给大家分享一个能通过代码主动生成文档技术,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-request
include::{snippets}/dog/curl-request.adoc[]

.http-request
include::{snippets}/dog/http-request.adoc[]

.request-fields
include::{snippets}/dog/request-fields.adoc[]

.response-body
include::{snippets}/dog/response-body.adoc[]

.response-fields
include::{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 更谨严。
正文完
 0