gpt4 book ai didi

java - MockMvc - 预期状态 :<200> but was:<302>

转载 作者:行者123 更新时间:2023-11-30 02:50:08 24 4
gpt4 key购买 nike

mockmvc测试junit时出现302错误。insertBoard类的重定向问题,我该怎么办。预期状态:<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());
}

最佳答案

您的测试正在验证调用/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"));
}

关于java - MockMvc - 预期状态 :<200> but was:<302>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38966718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com