官术网_书友最值得收藏!

How it works...

Our User class uses four of the new constraints introduced by Jakarta Bean Validation 2.0:

  • @NotBlank: This ensures that the value is not null, empty, or an empty string (it trims the value before evaluation, to make sure there aren't spaces).
  • @Email: This allows only a valid email format. Forget those crazy JavaScript functions!
  • @NotEmpty: This ensures that a list has at least one item.
  • @PositiveOrZero: This guarantees that a number is equal to or greater than zero.

Then, we create a test class (using JUnit) to test our validations. It first instantiates Validator, as follows:

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

Validator is an API that validates beans according to the constraints defined for them.

Our first test method tests a valid user, which is a User object that has the following:

  • Name not empty
  • Valid email
  • A profileId list only with integers greater than zero

This is shown in the following code snippet:

User user = new User(
"elder",
"elder@eldermoraes.com",
asList(1,2));

And finally, we have the validation:

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

The validate() method from Validator returns a set of constraint violations found, if any, or an empty set if there are no violations at all.

So, for a valid user, it should return an empty set:

assertTrue(cv.isEmpty());

For the other methods that work with variations around this model, we have the following:

  • invalidName(): Uses an empty name
  • invalidEmail(): Uses a malformed email
  • invalidId(): Adds some negative numbers to the list

Note that the invalidId() method adds two negative numbers to the list:

asList(-1,-2,1,2));

So, we expect two constraint violations:

assertEquals(2, cv.size());

In other words, Validator checks not only the constraints violated, but how many times they are violated.

主站蜘蛛池模板: 得荣县| 青冈县| 宁陕县| 杭锦旗| 许昌市| 和平区| 小金县| 博客| 清原| 厦门市| 布尔津县| 巴东县| 大渡口区| 南和县| 安陆市| 花莲市| 井陉县| 商丘市| 广元市| 吉隆县| 琼中| 手游| 开鲁县| 彭山县| 德格县| 电白县| 田阳县| 会东县| 年辖:市辖区| 京山县| 海城市| 太仆寺旗| 胶南市| 榆树市| 岳普湖县| 三台县| 涿州市| 璧山县| 蕲春县| 疏附县| 光泽县|