Hi i am following an example I found
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/
The problem is that no errors are found in my profile that I post. I should be. Why can this happend?
@Test
@Ignore
public void anotherTest() {
Profile profile = ProfileUtil.getProfile();
profile.setEmail("user@mail.com");
profile.setSex("dafjsgkkdsfa");
BindingResult bindingResult = new BeanPropertyBindingResult(profile, "profile");
userController.postUser(new ModelMap(), profile, bindingResult);
if (bindingResult.hasErrors()) {
System.out.println("errors");
}
assertTrue(bindingResult.hasErrors());
profileService.deleteProfile(profile);
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public View postUser(ModelMap data, @Valid Profile profile, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
System.out.println("No errors");
return dummyDataView;
}
data.put(DummyDataView.DATA_TO_SEND, "users/user-1.json");
profileService.save(profile);
return dummyDataView;
}
Edit: This is the Profile. I am testing the sex now so I guess thats what is important.
package no.tine.web.tinetips.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import no.tine.web.tinetips.util.CommonRegularExpressions;
import org.hibernate.validator.constraints.NotBlank;
@Entity
public class Profile {
@Id
@GeneratedValue
private Long id;
@NotNull(message = "profile.email.null")
@NotBlank(message = "profile.email.blank")
@Size(max = 60, message = "profile.email.maxlength")
@Pattern(regexp = CommonRegularExpressions.EMAIL, message = "profile.email.regex")
@Column(name = "Email", unique = true)
private String email;
@Pattern(regexp = "^[M|F]{1}$", message = "profile.sex.regex")
@Size(max = 1, message = "profile.sex.maxlength")
private String sex;
}
Basically you instantiated a POJO with this.userController = new UserController()
, then called its method this.controller.postUser(...)
. Just simple Java with a simple object, without any relation to Spring and Spring MVC : @Valid is not taken into account.
If you want to make it work, you will have to give your test class some Spring information, with @RunWith(SpringJUnit4ClassRunner.class)
and @ContextConfiguration(...)
. Then, for the Spring MVC part, you will have to mock a request call on your Controller through some Spring MVC facilites. It is done differently if you use Spring MVC 3.0- or 3.1+. For more information and actual code, see this post and its answers, for example.