kim
kim

Reputation: 31

MockMvc - status expected:<200> but was:<302>

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());
}

Upvotes: 3

Views: 10429

Answers (1)

Shawn Clark
Shawn Clark

Reputation: 3440

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"));
}

Upvotes: 4

Related Questions