前边spring boot mockmvc 已经可以简单的使用,这边文章主要是解决 web工程中 有注入情况下 如何测试
- 经过测试有两种方式 (具体原理没有深入研究,有了解的同学可以留言讨论)
1.注入controller
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
private MockMvc mockMvc;
@Autowired
private WebController webController;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(webController).build();
}
@Test
public void getUsers() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/getUsers")).andDo(MockMvcResultHandlers.print());
}
}
2.注入WebApplicationContext
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void getUsers() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/getUsers")).andDo(MockMvcResultHandlers.print());
}
}