springboot整合restdocs輸出介面文件

bluepeach發表於2021-09-09

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']

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2558/viewspace-2824780/,如需轉載,請註明出處,否則將追究法律責任。

相關文章