spring rest docs简介
通过单元测试自动生成asciidoc格式的碎片文档,通过asciidoctor-maven-plugin可转换成html的api说明文档。
构建步骤
1.在spring boot 项目的pom.xml文件中引入依赖
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
在写单元测试创建文档碎片的时候会使用到里面的类
2.在pom.xml中引入maven插件
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.github.mkgoingup</groupId>
<artifactId>docmerge-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<configuration>
<excludeDocFiles>curl-request.adoc,http-response.adoc</excludeDocFiles>
</configuration>
<goals>
<goal>merge</goal>
</goals>
<phase>prepare-package</phase>
</execution>
</executions>
</plugin>
<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>
<backend>html</backend>
<doctype>book</doctype>
</configuration>
</execution>
</executions>
</plugin>
这里一共引入了三个插件:maven-surefire-plugin、docmerge-maven-plugin、asciidoctor-maven-plugin
maven-surefire-plugin:打包的时候自动执行test目录下的单元测试,生成相应的碎片文件
docmerge-maven-plugin:合并这些碎片文件,生成一个完整的asciidoc格式的配置文件
asciidoctor-maven-plugin:将合并后配置文件转换成html的api文档
3.写单元测试
在单元测试的类上面加上@AutoConfigureMockMvc和@AutoConfigureRestDocs(outputDir = “target/generated-snippets”),然后自动注入一个MockMvc对像,通过这个对像创建文档
@RunWith(SpringRunner.class)
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
@AutoConfigureMockMvc
@SpringBootTest
public class ServiceTest {
@Autowired
private MockMvc mockMvc;
@Test
public void test1() throws Exception {
this.mockMvc.perform(get("/name"))
.andDo(print())
.andExpect(status().isOk())
.andDo(document("一、接口类型1/1.分类接口1"));
}
@Test
public void test2() throws Exception {
this.mockMvc.perform(get("/name"))
.andDo(print())
.andExpect(status().isOk())
.andDo(document("一、接口类型1/2.分类接口2"));
}
@Test
public void test3() throws Exception {
this.mockMvc.perform(get("/name"))
.andDo(print())
.andExpect(status().isOk())
.andDo(document("二、不分类接口3"));
}
}
4.通过maven打包(mvn package)生成接口文档,文档地址target/generated-docs下面,默认名称为openApi.html
docmerge-maven-plugin插件github地址,里面有详细说明
https://github.com/mkgoingup/spring-rest-docs-plugin