2013-07-30 97 views
1

我有一组实体类,它们是由Hibernate工具生成的。所有有@Column注释,如:如何使用JUnit测试验证实体类 - 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 { 私有静态验证验证;

@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

您的测试测试您的valiadation逻辑,而不是您的持久性逻辑。你想要测试什么行为? – Hippoom

+0

嗨,我想在我的代码的所有地方测试验证逻辑。这将防止持久逻辑无效。 –

回答

2

相信在@Column约束的目的不是做验证。它们用于生成DDL。所以你必须添加Hibernate-Validator注释来实现你的目标。

请参阅此post

相关问题