MockMvc编写单测
MockMvc
注意点
1、通过spring上下文获取mockmvc对象
@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
2、json处理
通过MockMvc发送和接受请求都是json。
所以发送请求的时候,需要将javabean转json
.content(new ObjectMapper().writeValueAsString(person)).contentType(MediaType.APPLICATION_JSON))
在接受得到result后,也需用json串转javabean。
Person person = new ObjectMapper().readValue(result.getResponse().getContentAsString(), Person.class);
code
待测试的controller
package com.lexiaoyao.mocktest.controller;
import com.lexiaoyao.mocktest.model.Person;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("test")
@Slf4j
public class TestController {
//通过正则限时id只能为数字
@GetMapping("/person/{id:\\d+}")
public ResponseEntity getPerson(@PathVariable("id") Integer id) {
return ResponseEntity.ok(new Person(id, "tom", 22));
}
@PostMapping("/person")
public ResponseEntity postPerson(@RequestBody Person person) {
return ResponseEntity.ok(person);
}
}
测试类
@SpringBootTest
@Slf4j
class MocktestApplicationTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
//在junit5内用BeforeEach代替Before
@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testGet() throws Exception {
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test/person/1")
//设置以json方式传输
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
//将MvcResult中的response转为对象
Person person = new ObjectMapper().readValue(result.getResponse().getContentAsString(), Person.class);
Assert.assertNotNull(person);
Assert.assertEquals(person.getId(), Integer.valueOf(1));
}
@Test
public void testPost() throws Exception {
Person person = new Person(10, "name", 2);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/test/person")
.content(new ObjectMapper().writeValueAsString(person)).contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
Person resultPerson = new ObjectMapper().readValue(result.getResponse().getContentAsString(), Person.class);
Assert.assertNotNull(person);
Assert.assertEquals(person.getId(), resultPerson.getId());
}
}