- Jakarta EE Cookbook
- Elder Moraes
- 184字
- 2021-06-24 16:12:34
How to do it...
We need to perform the following steps to try this recipe:
- First, we need to create an object with some fields to be validated:
public class User {
@NotBlank
private String name;
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;
}
}
- 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",
"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());
}
}
After this, let's see how the recipe works.
推薦閱讀
- ServiceNow Application Development
- Design Principles for Process:driven Architectures Using Oracle BPM and SOA Suite 12c
- Nginx Essentials
- Magento 1.8 Development Cookbook
- C語言課程設計
- Java程序員面試筆試寶典(第2版)
- Julia 1.0 Programming Complete Reference Guide
- Python程序設計與算法基礎教程(第2版)(微課版)
- 零基礎學Scratch 3.0編程
- Flink技術內幕:架構設計與實現原理
- Visual C++從入門到精通(第2版)
- INSTANT Apache Hive Essentials How-to
- Python數據可視化之matplotlib實踐
- Three.js Essentials
- 少年小魚的魔法之旅:神奇的Python