Spring MVC 3.2 Unit Test: No BindingResult for attribute "attr"
Hi Folks,
I am trying to unit test a controller
Here is the test: -
Code:
@Test
public void testRegisterMemberExists() throws Exception {
doThrow(new MemberExistsServiceException()).when(memberService).registerMember(any(String.class), any(String.class));
this.mockMvc.perform(
post("/register")
.param("email", "email@email.com")
.param("password", "password"))
.andExpect(status().isOk())
.andExpect(model().attributeHasErrors("email"));
}
Here is the method in question: -
Code:
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@Valid @ModelAttribute(SecurityRegisterModel.KEY) SecurityRegisterModel model, BindingResult result, HttpServletRequest aRequest) {
if (result.hasErrors()){
return LOGIN;
}
try{
memberService.registerMember(model.getEmail(), model.getPassword());
}catch (MemberExistsServiceException mese){
result.rejectValue("email", "member.email.exists");
return LOGIN;
}
return "redirect:/dashboard";
}
Here is the model: -
Code:
public class SecurityRegisterModel extends ABaseModel implements Serializable {
private static final long serialVersionUID = -3021884732426352101L;
public final static String KEY = "securityRegisterModel";
@Email
private String email;
@Size(min=7)
private String password;
@Override
public void reset() {
setEmail("");
setPassword("");
}
@Override
public String getKey() {
return KEY;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Through debugging I can see that the result.rejectValue line is called. I expected that to make the assertion "model().attributeHasErrors("email")" pass, but it doesn't.
I also checked model().attributeExists("email"), but that fails too. I'm not sure what the problem is.
Any ideas?
Thanks!
Ash