Steps:
- Create a new test class
- Add a class annotation @runwith (springrunner.class) @SpringbooTtest @webAppConfiguration to the test class
- Inject private @autowire private WebApplicationContext context;
- Define a private shared property private MockMvc Mock;
- Write a pre-test method for Junit (executed before testing the method, doing the preparatory work, @ Before) @ Before public void Before () throws the Exception {mock = MockMvcBuilders. WebAppContextSetup (context). The build (); }
- Test method in controller (example Test UserController_findAll) @test public void testFindAll(){MvcResult result = mock. Perform ( MockMvcRequestBuilders.get(‘/user’)) .andDo(MockMvcResultHandlers.print()) .andReturn();
General use form
ResultActions action = mock.perform(RequestBuilder);
action.andExpect(ResultMatcher)
.andDo(ResultHandler)
.andReturn();
Copy the code
interface RequestBuilder
Constructing a request
Need to use a method, which can be realized in the type of MockHttpServletRequestBuilder look up to
Excerpt part of the source code
/**
* Set the character encoding of the request.
* @param encoding the character encoding
*/
public MockHttpServletRequestBuilder characterEncoding(String encoding) {
this.characterEncoding = encoding;
return this;
}
/**
* Set the request body.
* @param content the body content
*/
public MockHttpServletRequestBuilder content(byte[] content) {
this.content = content;
return this;
}
/**
* Set the request body as a UTF-8 String.
* @param content the body content
*/
public MockHttpServletRequestBuilder content(String content) {
this.content = content.getBytes(StandardCharsets.UTF_8);
return this;
}
/**
* Set the 'Content-Type' header of the request.
* @param contentType the content type
*/
public MockHttpServletRequestBuilder contentType(MediaType contentType) {
Assert.notNull(contentType, "'contentType' must not be null");
this.contentType = contentType.toString();
return this;
}
Copy the code
Commonly used method
contentType(MediaType); content(String); param(String, String...) ; requestAttr(String, Object); accept(MediaType); headers(HttpHeaders);Copy the code
interfact ResultMatcher
Function interface, the result, conditional matching
In the org. Springframework. Test. Web. Servlet. The result of the * ResultMatchers package, defines the vast majority of return ResultMatcher method of anonymous implementation class
# all the classes ContentResultMatchers. Class CookieResultMatchers. Class FlashAttributeResultMatchers. Class HandlerResultMatchers.class HeaderResultMatchers.class JsonPathResultMatchers.class MockMvcResultHandlers.class MockMvcResultMatchers.class ModelResultMatchers.class PrintingResultHandler.class RequestResultMatchers.class StatusResultMatchers.class StatusResultMatchersExtensionsKt.class ViewResultMatchers.class XpathResultMatchers.classCopy the code
In order to **.andExpect(status().isOk())**Trace the source code for the case
// StatusResultMatchers.isOk()
/**
* Assert the response status code is {@code HttpStatus.OK} (200).
*/
public ResultMatcher isOk(a) {
return matcher(HttpStatus.OK);
}
/** * Match the expected response status to that of the HttpServletResponse. */
private ResultMatcher matcher(final HttpStatus status) {
return result -> assertEquals("Status", status.value(), result.getResponse().getStatus());
}
Copy the code
Parameters in.andexpect (ResultMatcher) are actually generated by static methods in MockMvcResultMatchers
//
/** * Access to response status assertions. */
public static StatusResultMatchers status(a) {
return new StatusResultMatchers();
}
Copy the code
interface ResultHandler
A functional interface to process the results obtained
The usual processing is to output to a log, or to the console, or to a specified output stream
It is recommended to use the method in MockMvcResultHandlers, which from the source code defines private static inner classes that extend PrintingResultHandler and ResultHandler
// Static methods in MockMvcResultHandlers that you can use
log();
print();
print(OutputStream);
print(Writer);
Copy the code
The sample
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class StationTest {
@Autowired
private WebApplicationContext context;
private MockMvc mock;
private String baseUrl = "/station";
private List<Station> list;
private MvcResult result;
private String id;
@Before
public void before(a) throws Exception {
mock = MockMvcBuilders.webAppContextSetup(context).build();
list = JsonUtil.toList(
mock.perform(get(baseUrl)).andReturn().getResponse().getContentAsString(),
Station.class);
System.err.println("\n==============================================================================\n");
id = list.get(0).getId();
}
@After
public void after(a) throws Exception {
SimpleLogUtil.error(result.getResponse().getContentAsString());
}
@Test
public void testFindAll(a) throws Exception {
result = mock.perform(MockMvcRequestBuilders.get(baseUrl))
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
list = JsonUtil.toList(result.getResponse().getContentAsString(), Station.class);
id = list.get(0).getId();
SimpleLogUtil.error(list);
}
@Test
public void testSave(a) throws Exception {
Station station = new Station(RCSUtil.CreateID(), "station-1".0.1."2"."1".20."10");
String json = JsonUtil.toJson(station);
result = mock
.perform(MockMvcRequestBuilders.post(baseUrl)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(json))
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
@Test
public void testGet(a) throws Exception {
result = mock.perform(MockMvcRequestBuilders.get(baseUrl + "/{id}", list.get(0).getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
@Test
public void testUpdate(a) throws Exception {
Station station = list.get(0);
station.setName("st-123");
station.setWalkType("0");
result = mock
.perform(MockMvcRequestBuilders.post(baseUrl + "/{id}". id) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(JsonUtil.toJson(station))) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andDo(MockMvcResultHandlers.print()) .andReturn(); }@Test
public void testDelete(a) throws Exception {
result = mock
.perform(MockMvcRequestBuilders.delete(baseUrl + "/{id}", id))
.andExpect(status().isOk())
.andExpect(content().string("true")) .andDo(MockMvcResultHandlers.print()) .andReturn(); }}@RestController
@RequestMapping("/station")
public class StationController {
@GetMapping("")
public List<Station> findAll(a) {
return service.findAll();
}
@PostMapping("")
public Station save(@RequestBody Station station) {
return service.save(station);
}
@GetMapping("/{id}")
public Station get(@PathVariable String id) {
return service.getById(id);
}
@PostMapping("/{id}")
public Station update(@RequestBody Station station, @PathVariable String id) {
station.setId(id);
return service.save(station);
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable String id) {
return service.delete(id);
}
@Autowired
private StationService service;
}
Copy the code