The following test cases are written for the Controller to verify the correctness, as follows. Of course, Request Submission validation can also be done through browser plug-ins and so on.
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MockServletContext.class) @WebAppConfiguration public class ApplicationTests { private MockMvc mvc; @Before public void setUp() throws Exception { mvc = MockMvcBuilders.standaloneSetup(new UserController()).build(); } @Test public void testUserController() throws Exception { // Test UserController RequestBuilder request = null; // 1. get checks the list of user s, which should be empty request = get("/users/"); mvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(equalTo("[]"))); // 2. post submits a user request = post("/users/") .param("id", "1") .param("name", "Test master") .param("age", "20"); mvc.perform(request) .andExpect(content().string(equalTo("success"))); // 3. get the list of user s, which should have the data just inserted request = get("/users/"); mvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"Test master\",\"age\":20}]"))); // 4. user whose put is modified to id 1 request = put("/users/1") .param("name", "Testing Ultimate Master") .param("age", "30"); mvc.perform(request) .andExpect(content().string(equalTo("success"))); // 5. get a user with id 1 request = get("/users/1"); mvc.perform(request) .andExpect(content().string(equalTo("{\"id\":1,\"name\":\"Testing Ultimate Master\",\"age\":30}"))); // 6. Delete user with id 1 request = delete("/users/1"); mvc.perform(request) .andExpect(content().string(equalTo("success"))); // 7. get checks the user list, which should be empty request = get("/users/"); mvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(equalTo("[]"))); } }
So far, by introducing the web module (without any other configuration), we can easily take advantage of Spring MVC's function and complete the creation of RESTful API for User objects and the writing of unit tests with very simple code. At the same time, some of the most commonly used core annotations in Spring MVC are introduced. @Controller RestController,RequestMapping, and annotations for parameter binding: @PathVariable,@ModelAttribute,@RequestParam, etc. Source Source Technology Support for Complete Project 1791743380