Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How mock BindingResult in/with Mockito

I have a controller method like this:

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

my test looks like this:

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

}

only thing what i want is to mock the bindingresult, the bindingResult.hasErrors() method should return false. Everytime i run this test the method return true.

Any suggestions how can i fix this error?

Thanks in advance

like image 356
Manu Zi Avatar asked Oct 31 '22 01:10

Manu Zi


1 Answers

Use this instead:

 @MockBean
 private BindingResult bindingResult;
like image 146
user11082855 Avatar answered Nov 09 '22 08:11

user11082855