2

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());
}

}

Dimitri Dewaele
  • 10,311
  • 21
  • 80
  • 127

1 Answers1

2

I believe the constraints in @Column does not aim to do validation. They're used to generate DDL. So you have to add Hibernate-Validator annotations to achieve your goal.

Refer to this post.

Community
  • 1
  • 1
Yugang Zhou
  • 7,123
  • 6
  • 32
  • 60