多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # 简介 ~~~ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> ~~~ * **MockMvc**允许我们方便的发送 HTTP 请求。 * **SpringBootTest**方便的创建一个 Spring Boot 项目的测试程序。 ~~~ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class HelloApplicationTests { @Autowired private MockMvc mvc; @Test public void contextLoads() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("Greetings from Spring Boot!")); } } ~~~ # 打印详细信息 ~~~ mockMvc.perform(MockMvcRequestBuilders.get("/hello?name=⼩小明") .accept(MediaType.APPLICATION_JSON)).andDo(print()); ~~~ # 打印返回值 ~~~ String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/hello?name=⼩小明") .accept(MediaType.APPLICATION_JSON_UTF8)) .andReturn().getResponse().getContentAsString(); System.out.println(responseString); ~~~