如何在 Mockito 中模拟 BindingResult

Man*_* Zi 5 spring unit-testing mocking spring-mvc mockito

我有一个这样的控制器方法:

@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);
}
Run Code Online (Sandbox Code Playgroud)

我的测试是这样的:

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

}
Run Code Online (Sandbox Code Playgroud)

我唯一想要的是模拟 bindingresult,该bindingResult.hasErrors()方法应该返回 false。每次我运行此测试时,该方法都会返回 true。

任何建议如何解决此错误?

提前致谢

小智 0

你不能,这也不是 Mock MVC 的工作原理。

您应该提交有效的请求...模拟不起作用。