Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit testing for annotated controller

How could I test following method in my controller

@RequestMapping(method = RequestMethod.POST)
    public String register(@Valid User user, BindingResult result) {

        if (result.hasErrors()) {
            return "users/registration";
        }

        // create user
        service.create(user);

        return "redirect:/";
    }

How could I test the @Valid and the BindingResult?

public void testRegister() {
        try {
        request.setMethod("POST");
        request.setRequestURI("/users");
            request.setParameter("email", "[email protected]");
        request.setParameter("prename", "Cyril");
        request.setParameter("surname", "bla");
        request.setParameter("password", "123");
        request.setParameter("repeat", "123");
        request.setParameter("birthdate", "2000-01-01");
        request.setParameter("city", "Baden");


            ModelAndView mAv = adapter.handle(request, response, usersController);

            assertEquals("redirect:/", mAv.getViewName());
        } catch (Exception e) {
            fail();
        }
    }

thx a lot

like image 638
gabac Avatar asked May 19 '26 11:05

gabac


1 Answers

For the @Valid annotation, that's outside the scope of your unit test. You can trust that the Spring Framework will perform the validation for you, setting the BindingResult appropriately.

So really, you just need to cover your if check of result.hasErrors() - and for that, you should be mocking the BindingResult; here's how to do it with Mockito:

...
@Mock
private BindingResult mockBindingResult

@Before
public void setupTest() {
    MockitoAnnotations.initMocks(this);
    // While the default boolean return value for a mock is 'false',
    // it's good to be explicit anyway:  
    Mockito.when(mockBindingResult.hasErrors()).thenReturn(false);
}

@Test
public void shouldStayOnRegistrationPageIfBindingErrors() {
    // Simulate having errors just for this test:
    Mockito.when(mockBindingResult.hasErrors()).thenReturn(true);

    ModelAndView mav = controller.register(user, mockBindingResult);

    // Check that we returned back to the original form:
    assertEquals("users/registration", mav.getViewName());
}

I also find it's really good to use Cobertura (and especially the eCobertura Eclipse plugin) to visually confirm that every line and branch is covered by unit tests.

like image 111
millhouse Avatar answered May 22 '26 06:05

millhouse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!