controller的单元测试

https://stackoverflow.com/questions/38966718/mockmvc-status-expected200-but-was302

The 302 error occurred during mockmvc test junit. The redirect issue of insertBoard class,what should i do. status expected:<200> but was:<302>

@RequestMapping(value="/sample/insertBoard.do")
public ModelAndView insertBoard(CommandMap commandMap,HttpServletRequest request) throws Exception{
    ModelAndView mv = ModelAndView("redirect:/sample/openBoardList.do");
    sampleService.insertBoard(commandMap.getMap(),request);
    return mv;
}

@Test
public void testInsertBoard() throws Exception{
    File fis = new File("c:\\users\\aaa.jpg");
    FileInputStream fi1 = new FileInputStream(fis);
    MockMultipartFile file = new MockMultipartFile("file",fis.getName(),"multipart/form-data",fi1);

    this.mockMvc.perform(MockMvcRequestBuilders.fileupload("/sample/insertBoard.do"))
                .file(file)
                .param("title","title_test")
                .param("contents","contents_test")
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .andExpect(status().isOk());
}

 

Your test is validating what is returned from the call to /sample/insertBoard.do. MockMvc doesn't follow redirects so the 302 is valid as it is means that the browser should go to the new url when the response is returned. You would want to verify that the redirect is correct by using redirectedUrl("/sample/openBoardList.do") instead of the status().isOk().

Including an updated example... hopefully that helps in understanding the change:

@Test
public void testInsertBoard() throws Exception{
    File fis = new File("c:\\users\\aaa.jpg");
    FileInputStream fi1 = new FileInputStream(fis);
    MockMultipartFile file = new MockMultipartFile("file",fis.getName(),"multipart/form-data",fi1);

    this.mockMvc.perform(MockMvcRequestBuilders.fileupload("/sample/insertBoard.do"))
            .file(file)
            .param("title","title_test")
            .param("contents","contents_test")
            .contentType(MediaType.MULTIPART_FORM_DATA)
            .andExpect(redirectedUrl("/sample/openBoardList.do"));
}

重定向的测试不同,不能用status().isOK()而应该用status().isFound()

转载于:https://my.oschina.net/u/1389868/blog/3006145

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值