1

I have a set of Entity Classes, which are generated by Hibernate tools. All have @Column annotations like:

@Column(name = "CNTR_DESCRIPTION", nullable = false, length = 5)
public String getDescription() {
    return this.description;
}

I want to write a JUnit test to validate my input to the database, but validation with JUnit only works when adding:

@NotNull
@Size(max = 5)
@Column(name = "CNTR_DESCRIPTION", nullable = false, length = 5)
public String getDescription() {
    return this.description;
}

I prefer NOT to add any annotations, since then I need to change the automatic generated Entity Classes. How Can I get the JUnit test working with the first generated @Column annotations? Thanks!

My JUnit test (does not work with only @Column, but does work with the extra @NotNull and @Size):

public class CountryEntityTest { private static 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());
}

}

4

1 回答 1

2

我相信@Column 中的约束并非旨在进行验证。它们用于生成 DDL。所以你必须添加 Hibernate-Validator 注释来实现你的目标。

参考这篇文章

于 2013-07-31T08:43:36.983 回答