hibernate - 如何使用 JUnit 测试验证实体类 - Hibernate @Column 注释

标签 hibernate class validation junit entity

我有一组实体类,它们是由 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/

相关文章:

java - Hibernate继承(TABLE_PER_CLASS)表扩展

java - Hibernate集合持久化

c++ - 另一个包含的对象如何改变容器对象的私有(private)数据成员?

python - 解析文本文件以存储到类对象和属性中

validation - Monaco Editor 中自定义语言的语法验证

javascript - 信用卡验证问题

php - 为什么我无法覆盖默认的验证错误消息?

java - Hibernate 5.2 中的示例查询

java - 如何使用Spring boot通过post方法在postman中发送2个不同的对象?

python - 如何通过继承在两个不同的类中拆分函数?初学者