我有一组实体类,它们是由Hibernate工具生成的。所有人都有@Column注释,如:
@Column(name = "CNTR_DESCRIPTION", nullable = false, length = 5)
public String getDescription() {
return this.description;
}
我想编写一个JUnit测试来验证我对数据库的输入,但是使用JUnit进行验证只在添加时有效:
@NotNull
@Size(max = 5)
@Column(name = "CNTR_DESCRIPTION", nullable = false, length = 5)
public String getDescription() {
return this.description;
}
我不想添加任何注释,因为那时我需要更改自动生成的实体类。 如何使用第一个生成的@Column注释来使用JUnit测试? 谢谢!
我的JUnit测试(不仅适用于@Column,但可以使用额外的@NotNull和@Size):
公共类CountryEntityTest { private static Validator验证器;
@BeforeClass
public static void setUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void countryDescriptionIsNull() {
CountryEntity country = new CountryEntity();
country.setDescription(null);
Set<ConstraintViolation<CountryEntity>> constraintViolations = validator.validate( country );
assertEquals( 1, constraintViolations.size() );
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );
}
@Test
public void countryDescriptionSize() {
CountryEntity country = new CountryEntity();
country.setDescription("To long");
Set<ConstraintViolation<CountryEntity>> constraintViolations = validator.validate( country );
assertEquals( 1, constraintViolations.size() );
assertEquals( "size must be between 0 and 5", constraintViolations.iterator().next().getMessage());
}
}
答案 0 :(得分:2)
我相信@Column中的约束并不旨在进行验证。他们习惯于生成DDL。因此,您必须添加Hibernate-Validator注释才能实现目标。
请参阅此post。