2016-08-16 47 views
0

mockmvc測試junit期間發生302錯誤。 insertBoard類的重定向問題,我該怎麼做。 狀態預計:< 200>卻被:< 302>MockMvc - 預計狀態:<200>但是:<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()); 
} 

回答

2

你的測試驗證什麼是從調用返回到/sample/insertBoard.do。 MockMvc不遵循重定向,所以302有效,因爲這意味着瀏覽器在返回響應時應該轉到新的url。您需要使用redirectedUrl("/sample/openBoardList.do")而不是status().isOk()來驗證重定向是否正確。

包括更新的例子......希望這有助於理解的變化:

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

對不起。我無法理解。 只是我想testInsertBoard測試成功。 – kim

相關問題