Reputation: 2078
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
Upvotes: 3
Views: 5966
Reputation: 10007
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.
Upvotes: 3