How to do it...

We need to perform the following steps to try this recipe:

  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 UserTest 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",
"[email protected]",
asList(1,2));

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

@Test
public void invalidName() {
User user = new User(
"",
"[email protected]",
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",
"[email protected]",
asList(-1,-2,1,2));

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

After this, let's see how the recipe works.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.192.3