Java EE 8 Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. First, we need to create an object with some fields to be validated:
public class User {

@NotBlank
private String name;

@Email
private String email;

@NotEmpty
private List<@PositiveOrZero Integer> profileId;

public User(String name, String email, List<Integer> profileId) {
this.name = name;
this.email = email;
this.profileId = profileId;
}
}
  1. Then we create a test class to validate those constraints:
public class UserTest {

private static Validator validator;

@BeforeClass
public static void setUpClass() {
validator = Validation.buildDefaultValidatorFactory()
.getValidator();
}

@Test
public void validUser() {
User user = new User(
"elder",
"elder@eldermoraes.com",
asList(1,2));

Set<ConstraintViolation<User>> cv = validator
.validate(user);
assertTrue(cv.isEmpty());
}

@Test
public void invalidName() {
User user = new User(
"",
"elder@eldermoraes.com",
asList(1,2));

Set<ConstraintViolation<User>> cv = validator
.validate(user);
assertEquals(1, cv.size());
}

@Test
public void invalidEmail() {
User user = new User(
"elder",
"elder-eldermoraes_com",
asList(1,2));

Set<ConstraintViolation<User>> cv = validator
.validate(user);
assertEquals(1, cv.size());
}

@Test
public void invalidId() {
User user = new User(
"elder",
"elder@eldermoraes.com",
asList(-1,-2,1,2));

Set<ConstraintViolation<User>> cv = validator
.validate(user);
assertEquals(2, cv.size());
}
}