知乎专栏 |
创建测试类,在测试类的类头部添加:@RunWith(SpringRunner.class)、@SpringBootTest、@ AutoConfigureMockMvc注解,在测试方法的前添加@Test,最后选择方法右键run运行。
使用@Autowired 注入MockMvc,在方法中使用 mvc测试功能。示例:
@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class StudentControllerTest { @Autowired private MockMvc mvc; @Test public void getAll() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/student/getAll")).andExpect(MockMvcResultMatchers.model().attributeExists("students")); } @Test public void save() throws Exception { Student student = new Student(); student.setAge(12); student.setId("1003"); student.setName("Neo"); mvc.perform(MockMvcRequestBuilders.post("/student/save", student)); } @Test public void delete() throws Exception { mvc.perform(MockMvcRequestBuilders.delete("/student/delete?id=1002")); } @Test public void index() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/student/index")).andReturn(); } }