spring-boot-starter-test
排除Junit4
springboot2.2.x以下的版本,只包含junit4.x的版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/>
</parent>
引入test
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
引入2.2.x以上的springboot则包含Junit4.x和Junit5.x两个版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
使用springboot-test时查看使用的版本中是否同时包含两个版本,如果都包含则可以排除Junit4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
MockMvc测试接口
编写一个get接口,调用了service层,无需启动服务器
@Autowired
private TestService testService;
@GetMapping(value = "/test1")
public String test1() {
testService.test1();
return "success";
}
public void test1(){}//service
测试get请求 @SpringBootTest 会根据路径寻找 @SpringBootApplication 或 @SpringBootConfiguration所以请保持test目录结构与main目录结构相同。否则要
使用@SpringBootTest(classes="Application.class")主动标记启动类。
@SpringBootTest
@AutoConfigureMockMvc
public class TestController {
@Autowired
private MockMvc mvc;
@Test
public void test1() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/test1")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().string("success"));
}
}
@MockBean模拟bean
编写一个get接口,调用了service层,在service返回字符串service1
@Autowired
private TestService testService;
@GetMapping(value = "test")
public String test() {
return testService.service1();
}
public String service1(){
return "service1";
}
通过@MockBean注入TestService。使用BDDMockito.given()给service1()重新搞一个返回值。这个请求返回的是mockvalue而不是service1。事实上将service类上
的@Service注解去掉,即没有这个业务bean这个测试类也会成功运行。
@MockBean
private TestService remoteService;
@Test
public void test2() throws Exception {
given(this.remoteService.service1()).willReturn("mockvalue");
String contentAsString = mockMvc.perform(MockMvcRequestBuilders.get("/test"))
.andReturn().getResponse().getContentAsString();
System.out.println("!!!!!!!!!!!!!!!!"+contentAsString);
}
@JsonTest测试JSON
JacksonTester的功能和JSONObject类似。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class VehicleDetails {
private String make;
private String model;
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
@JsonTest
public class TestController2 {
@Autowired
private JacksonTester<VehicleDetails> json;
@Test
void testDeserialize() throws Exception {
String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}";
VehicleDetails vehicleDetails = this.json.parseObject(content);
System.out.println(vehicleDetails.getMake()+""+vehicleDetails.getModel());
}
addReturn()
设置MediaType,设置Head.addReturn()返回请求结果.
@SpringBootTest @AutoConfigureMockMvc public class TestController { @Autowired MockMvc mvc; @Test public void test2()throws Exception{ Person p = new Person(); p.setName("张三"); p.setAge(11); MockHttpServletResponse response = mvc.perform(MockMvcRequestBuilders.post("/test2").contentType(MediaType.APPLICATION_JSON) .content(JSONObject.toJSONString(p)).header("test-head", "head-value")).andReturn().getResponse(); String contentAsString = response.getContentAsString(Charset.forName("utf-8")); System.out.println(response.getHeader("test2-head")); System.out.println(contentAsString); } }
@PostMapping(value = "test2") public Person test2(@RequestBody Person person, HttpServletRequest request, HttpServletResponse response) { System.out.println("!!!!!!!!!!!!!"+person); System.out.println("!!!!!!!!!!!!!"+request.getHeader("test-head")); response.addHeader("test2-head","headvalue"); return testService.testService(person); }
andDo()
好像只能打印请求
@SpringBootTest @AutoConfigureMockMvc public class TestController { @Autowired MockMvc mvc; @Test public void test3() throws Exception { Person p = new Person(); p.setName("张三"); p.setAge(11); ResultActions actions = mvc.perform(MockMvcRequestBuilders.post("/test2") .contentType(MediaType.APPLICATION_JSON).content(JSONObject.toJSONString(p))); actions.andReturn().getResponse().setCharacterEncoding("utf-8"); actions.andDo(MockMvcResultHandlers.print()); } }
MockHttpServletRequest: HTTP Method = POST Request URI = /test2 Parameters = {} Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"26"] Body = {"age":11,"name":"张三"} Session Attrs = {} Handler: Type = com.datang.qqboark.controller.DemoController Method = com.datang.qqboark.controller.DemoController#test2(Person, HttpServletRequest, HttpServletResponse) Async: Async started = false Async result = null Resolved Exception: Type = null ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 200 Error message = null Headers = [test2-head:"headvalue", Content-Type:"application/json;charset=utf-8"] Content type = application/json Body = {"name":"张三","age":11} Forwarded URL = null Redirected URL = null Cookies = []
andExpect()
增加断言MockMvcResultMatchers断言HTTP状态,断言head,断言返回值.
@SpringBootTest @AutoConfigureMockMvc public class TestController { @Autowired MockMvc mvc; @Test public void test4() throws Exception { Person p = new Person(); p.setName("张三"); p.setAge(11); ResultActions actions = mvc.perform(MockMvcRequestBuilders.post("/test2") .contentType(MediaType.APPLICATION_JSON).content(JSONObject.toJSONString(p))); actions.andReturn().getResponse().setCharacterEncoding("utf-8"); actions.andExpect(MockMvcResultMatchers.status().isOk()); actions.andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); actions.andExpect(MockMvcResultMatchers.header().string("test2-head","headvalue")); actions.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)); actions.andExpect(MockMvcResultMatchers.content().json(JSONObject.toJSONString(p))); } }