我有一组实体类,它们是由 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;
}
我不想添加任何注释,因为那样我需要更改自动生成的实体类。 如何让 JUnit 测试使用第一个生成的 @Column 注释? 谢谢!
我的 JUnit 测试(不仅仅适用于 @Column,但适用于额外的 @NotNull 和 @Size):
公共(public)类CountryEntityTest { 私有(private)静态Validator 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());
}
}
最佳答案
我相信@Column中的约束并不是为了进行验证。它们用于生成 DDL。所以你必须添加 Hibernate-Validator 注解来实现你的目标。
引用这个post .
关于hibernate - 如何使用 JUnit 测试验证实体类 - Hibernate @Column 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17948928/