packagecom.test.demo;
importcom.test.demo.controller.IndexController;
importorg.junit.jupiter.api.*;//注意这里,这是junit5引入的;junit4引入的是org.junit.Test这样类似的包
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.http.MediaType;
importorg.springframework.test.web.servlet.MockMvc;
importorg.springframework.test.web.servlet.MvcResult;
importorg.springframework.test.web.servlet.RequestBuilder;
importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;
importorg.springframework.test.web.servlet.result.MockMvcResultHandlers;
importorg.springframework.test.web.servlet.result.MockMvcResultMatchers;
importorg.springframework.test.web.servlet.setup.MockMvcBuilders;
importorg.springframework.web.context.WebApplicationContext;
//这里只写SpringBootTest这个注解;如果是junit4的话,就要加上@RunWith(SpringRunner.class)
@SpringBootTest
classDemoApplicationTests{
privatestaticfinalLoggerLOG=LoggerFactory.getLogger(DemoApplicationTests.class);
privateMockMvcmockMvc;
@Autowired
privateWebApplicationContextwebApplicationContext;
@Test
voidcontextLoads(){
}
@BeforeAll
publicstaticvoidbeforeAll(){
LOG.info("beforeAll");
}
@BeforeEach
publicvoidbeforeEach(){
LOG.info("beforeEach");//mockMvc=MockMvcBuilders.standaloneSetup(newIndexController()).build();
mockMvc=MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@AfterEach
publicvoidafterEach(){
LOG.info("afterEach");
}
@AfterAll
publicstaticvoidafterAll(){
LOG.info("afterAll");
}
@Test
publicvoidtestTwo()throwsException{
RequestBuilderrequest=MockMvcRequestBuilders.get("/index/getData")
.param("searchPhrase","ABC")//传参
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);//请求类型JSON
MvcResultmvcResult=mockMvc.perform(request)
.andExpect(MockMvcResultMatchers.status().isOk())//期望的结果状态200
.andDo(MockMvcResultHandlers.print())//添加ResultHandler结果处理器,比如调试时打印结果(print方法)到控制台
.andReturn();//返回验证成功后的MvcResult;用于自定义验证/下一步的异步处理;
intstatus=mvcResult.getResponse().getStatus();//得到返回代码
Stringcontent=mvcResult.getResponse().getContentAsString();//得到返回结果
LOG.info("status:"+status+",content:"+content);
}
}