- Jakarta EE Cookbook
- Elder Moraes
- 295字
- 2021-06-24 16:12:35
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.
- Data Visualization with D3 4.x Cookbook(Second Edition)
- Delphi程序設計基礎:教程、實驗、習題
- Java 開發從入門到精通(第2版)
- 軟件架構設計:大型網站技術架構與業務架構融合之道
- MongoDB for Java Developers
- PHP網絡編程學習筆記
- Python金融數據分析
- HTML5入門經典
- 微信小程序項目開發實戰
- 數據結構習題解析與實驗指導
- 程序設計基礎教程:C語言
- Visual Basic程序設計實驗指導(第二版)
- Mobile Device Exploitation Cookbook
- C# and .NET Core Test Driven Development
- 零基礎學Python編程(少兒趣味版)