使用MockMvc进行controller接口单元测试

标签:ring   单元测试   单元   result   ext   注解   contexts   extc   stat   

1.添加注解@RunWith @ContextConfiguration @WebAppConfiguration
[email protected] 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<String, String>  paraMap = new LinkedMultiValueMap<>();
       paraMap.add("userName", "mockMVC");
       paraMap.add("userPswd", "123456");
       paraMap.add("email", "[email protected]");
       paraMap.add("loginAcct", "会员");
        final MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/user/reg.do").contentType(MediaType.APPLICATION_FORM_URLENCODED).params(paraMap)).andReturn();
        System.out.println(mvcResult.getResponse().getStatus());
    }

    @Test
    public void testUserLogin() throws Exception {
        LinkedMultiValueMap<String, String> paraMap = new LinkedMultiValueMap<>();
        paraMap.add("userName", "mockMVC");
        paraMap.add("userPswd", "123456");
        final MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/user/login.do").contentType(MediaType.APPLICATION_FORM_URLENCODED).params(paraMap)).andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();
        int status = response.getStatus();
        System.out.println("response status: " + status);
        Cookie[] cookies = response.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println("cookie: " + cookie.getComment());
        }
    }

 

使用MockMvc进行controller接口单元测试

标签:ring   单元测试   单元   result   ext   注解   contexts   extc   stat   

原文地址:https://www.cnblogs.com/hello4world/p/12865979.html