在我最近的工作中,我使用了spring-data-jpa来利用提供的存储库.当涉及集成测试时,我无法配置(我假设)测试的spring上下文,并且作为结果bean验证在我的测试中不起作用.
我知道我可以注入验证器,并对我的注释进行单元测试,但事实并非如此.我正在编写集成测试,并希望在支持DB的情况下测试存储库.
我准备了简单的项目来显示所有必要的项目文件.
当我运行测试时,2会失败并且我不知道为什么,类路径上存在hibernate验证器.
Failed tests: insertWrongEmail(com.example.core.data.jpa.UserRepositoryTest): Expected ConstraintViolationException wasn't thrown.
insertToShortPassword(com.example.core.data.jpa.UserRepositoryTest): Expected ConstraintViolationException wasn't thrown.
Run Code Online (Sandbox Code Playgroud)
[..]
Apr 23, 2013 5:00:08 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 4.3.1.Final
Run Code Online (Sandbox Code Playgroud)
源代码和mvn测试输出如下.
预先感谢您的帮助.
Java类(我删除了注释,geters,seters,equals,hashCode,toString等):
BaseEntity
package com.example.core.data.jpa;
import javax.persistence.*;
@MappedSuperclass
public abstract class BaseEntity {
public static final String SEQUENCE = "global_seq";
@Id
@SequenceGenerator(name = SEQUENCE, sequenceName = SEQUENCE)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
@Column(name = "id")
private Long id;
public Long getId() {
return id;
}
}
Run Code Online (Sandbox Code Playgroud)
用户 …
我想我刚刚发现两个不同的JPA实现在约束违规和回滚方面的工作方式不同.
@Test(expectedExceptions = @@.class) // CVE or RB?
public void testXXX() {
final EntityManager manager = LocalPU.createEntityManager();
try {
final EntityTransaction transaction = manager.getTransaction();
transaction.begin();
try {
manager.persist(<wrong>); // this is where CVE coming from
transaction.commit(); // this is where RB coming from
} catch (RollbackException re) {
// <---------------------------------------- hibernate here
throw re;
} catch (ConstraintViolationException cve) {
// <---------------------------------------- eclipselink here
transaction.rollback();
throw cve;
} catch (Exception e) {
transaction.rollback();
e.printStackTrace(System.err);
Assert.fail(e.getMessage());
}
} finally {
manager.close();
} …Run Code Online (Sandbox Code Playgroud)