電子商務社交平臺源碼請加企鵝求求:叄五叄六貳四柒貳五九。這篇文章將帶你瞭解如何用spring官方推薦的restdoc去生成api文檔。本文建立一個簡單的springboot工程,將http接口經過Api文檔暴露出來。只須要經過 JUnit單元測試和Spring的MockMVC就能夠生成文檔。web
準備工做
你須要15min
Jdk 1.8
maven 3.0+
idea
建立工程
引入依賴,其pom文件:spring
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <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> </dependencies>
經過@SpringBootApplication,開啓springbootapi
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
在springboot一般建立一個controller:瀏覽器
@RestController public class HomeController { @GetMapping("/") public Map<String, Object> greeting() { return Collections.singletonMap("message", "Hello World"); } }
啓動工程,訪問localhost:8080,瀏覽器顯示:springboot
{「message」:」Hello World」}
證實接口已經寫好了,可是如何經過restdoc生存api文檔呢mvc
Restdoc,經過單元測試生成api文檔
restdocs是經過單元測試生存snippets文件,而後snippets根據插件生成htm文檔的。app
建一個單元測試類:curl
@RunWith(SpringRunner.class) @WebMvcTest(HomeController.class) @AutoConfigureRestDocs(outputDir = "target/snippets") public class WebLayerTest { @Autowired private MockMvc mockMvc; @Test public void shouldReturnDefaultMessage() throws Exception { this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk()) .andExpect(content().string(containsString("Hello World"))) .andDo(document("home")); } }
其中,@ AutoConfigureRestDocs註解開啓了生成snippets文件,並指定了存放位置。maven
啓動單元測試,測試經過,你會發如今target文件下生成了一個snippets文件夾,其目錄結構以下:ide
└── target └── snippets └── home └── httpie-request.adoc └── curl-request.adoc └── http-request.adoc └── http-response.adoc
電子商務社交平臺源碼請加企鵝求求:叄五叄六貳四柒貳五九