使用MockMvc进行controller接口单元测试
2021-03-09 03:28
标签:ring 单元测试 单元 result ext 注解 contexts extc stat 1.添加注解@RunWith @ContextConfiguration @WebAppConfiguration 例子: 使用MockMvc进行controller接口单元测试 标签:ring 单元测试 单元 result ext 注解 contexts extc stat 原文地址:https://www.cnblogs.com/hello4world/p/12865979.html
2.@Autowired WebApplicationContext wac,让spring自动装配WebApplicationContext对象
3.获取MockMvc对象 MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac).build()
4.执行post请求测试。
MultiValueMap paraMap = new LinkedMultiValueMap();
paraMap.add // 添加请求参数和值
MvcResult mr = mockMvc.perform(MockMvcRequestBuilders.post("/user/login.do").contentType(MediaType.APPLICATION_FORM_URLENCODED).params(paraMap)).andReturn();
MockHttpServletResponse response = mr.getResponse();
可以获取比如响应码 response.getStatus()@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:springmvc4test.xml", "classpath:mybatisconfig.xml"})
@WebAppConfiguration
public class UserControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void init() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void testUserReg() throws Exception {
MultiValueMap
文章标题:使用MockMvc进行controller接口单元测试
文章链接:http://soscw.com/index.php/essay/62107.html