我有一个像这样的控制器方法:
@RequestMapping(value = "/{userId}/edit", method = RequestMethod.POST)
public ModelAndView updateUser(@PathVariable(USER_ID_PATH_VAR) final long userId, @Valid @ModelAttribute(MODEL_USER_WEB) final User user, BindingResult bindingResult,
final Principal principal, final Model model, @RequestParam(value = "otherLocation", required = false) Boolean isOnlyOneLocation) {
if (bindingResult.hasErrors()) {
return new ModelAndView(URL_EDIT_USER);
}
// do something ...
return new ModelAndView(URL_FINISH_USER);
}
我的测试看起来像这样:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ManageUsersControllerTestConfig.class})
public class ManageUserControllerTest {
@Autowired
private ManageUserController userController;
@Autowired
private Model model;
private MockMvc mockMvc;
@Autowired
private BindingResult bindingResult;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".html");
mockMvc = MockMvcBuilders
.standaloneSetup(userController)
.setViewResolvers(viewResolver)
.build();
}
@Test
public void testUpdateInstitutionWithErrors() throws Exception {
when(bindingResult.hasErrors()).thenReturn(false);
mockMvc.perform(post(WebSecurityConfig.URL_USER_OVERVIEW + "/" + USER_ID + "/" + URL_PART_EDIT)
.param(USER_ID_PATH_VAR, USER_ID))
.andExpect(status().isOk())
.andDo(print());
}
}
我想要的只是模仿bindingresult,bindingResult.hasErrors()
方法应该返回false。每次运行此测试时,该方法都返回true。
有任何建议如何解决此错误?
提前致谢
答案 0 :(得分:0)
改为使用此:
@MockBean
private BindingResult bindingResult;
答案 1 :(得分:0)
您不能,那不是Mock MVC的工作方式。
您应该提交有效的请求...模拟无效。
答案 2 :(得分:0)
我遇到了类似的情况,我在getModelAndView中发现bindingResult
示例
ModelAndView mockResult=mockMvc
.perform(MockMvcRequestBuilders.post(YOURL_URL))
.andReturn().getModelAndView();
BindingResult BindingResult= (BindingResult)mockResult.getModel().get("org.springframework.validation.BindingResult.YourForm")