1. 90前端首页
  2. 前端开发
  3. JavaScript

springboot集成restdocs输出接口文档

1、pom文件新增restdocs

<dependency>                  
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>    
<scope>test</scope>
</dependency>
<plugin>    
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>    
<version>1.5.8</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>    
<dependencies>        
    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-asciidoctor</artifactId>
        <version>${spring-restdocs.version}</version>
    </dependency>    
</dependencies>
</plugin>

2、在test包下新建controller

@RunWith(SpringRunner.class)
@SpringBootTestpublic class ApiBaseController {    

    @Rule    
    public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();    
    
    public MockMvc mockMvc;    
    
    @Autowired    
    private WebApplicationContext context;    
    
    @Before    
    public void setUp() {        
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
                    .apply(documentationConfiguration(this.restDocumentation))
                    .build();   
    }
}

3、新建单元测试

public class TestController extends ApiBaseController {
    @Test    
    public void test() throws Exception  {        
        super.mockMvc.perform(post(\"/test\").param(\"aaa\", \"bbb\")                
                        .contentType(MediaType.APPLICATION_JSON))                
                        .andDo(document(\"{ClassName}/{methodName}\", 
                        preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()),                        
                        requestParameters(parameterWithName(\"aaa\").description(\"查询名字\"))));    
     }
 }

4、运行后会在targetgenerated-snippets生成adoc文件
5、在main下新建asciidoc包,新建index.adoc 拼接已经生成的adoc

= API:toc: 
left:toclevels: 4
[[order-it]]
== 1. 订单接口
[[order-query]]
=== 订单查询
operation::TestController/test[snippets=\'curl-request,http-request\']

本文来自网络整理,转载请注明原出处:https://segmentfault.com/a/1190000021627091

展开阅读全文

发表评论

登录后才能评论