上QQ阅读APP看书,第一时间看更新
Writing the Test method
The complete Test method is shown in the following code:
@Test
public void basicTest() throws Exception {
this.mockMvc
.perform(
get("/welcome")
.accept(MediaType.parseMediaType
("application/html;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect( content().contentType
("application/html;charset=UTF-8"))
.andExpect(content().
string("Welcome to Spring MVC"));
}
A few important things to note are as follows:
- MockMvc mockMvc.perform: This method executes the request and returns an instance of ResultActions that allows chaining calls. In this example, we are chaining the andExpect calls to check expectations.
- get("/welcome").accept(MediaType.parseMediaType("application/html;charset=UTF-8")): This creates an HTTP get request accepting a response with the media type application/html.
- andExpect: This method is used to check expectations. This method will fail the test if the expectation is not met.
- status().isOk(): This uses ResultMatcher to check whether the response status is that of a successful request - 200.
- content().contentType("application/html;charset=UTF-8")): This uses ResultMatcher to check whether the content type of the response is as specified.
- content().string("Welcome to Spring MVC"): This uses ResultMatcher to check whether the response content contains the specified string.