保存重复对象时,JPA DAO 集成测试不会引发异常?
我正在对使用 Spring/JPA 和 Hibernate 作为提供者构建的 DAO 进行单元测试。
在运行测试之前,DBUnit 插入了一条用户名为“poweruser”的用户记录——用户名是用户表中的主键。这是集成测试方法:
@Test
@ExpectedException(EntityExistsException.class)
public void save_UserTestDataSaveUserWithPreExistingId_EntityExistsException() {
User newUser = new UserImpl("poweruser");
newUser.setEmail("[email protected]");
newUser.setFirstName("New");
newUser.setLastName("User");
newUser.setPassword("secret");
dao.persist(newUser);
}
我已经在该方法开始时验证了该记录位于数据库中。不确定这是否相关,但如果我在此方法末尾执行 dao.flush()
,则会出现以下异常:
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException:
Could not execute JDBC batch update
I am in the process of unit testing a DAO built with Spring/JPA and Hibernate as the provider.
Prior to running the test, DBUnit inserted a User record with username "poweruser" -- username is the primary key in the users table. Here is the integration test method:
@Test
@ExpectedException(EntityExistsException.class)
public void save_UserTestDataSaveUserWithPreExistingId_EntityExistsException() {
User newUser = new UserImpl("poweruser");
newUser.setEmail("[email protected]");
newUser.setFirstName("New");
newUser.setLastName("User");
newUser.setPassword("secret");
dao.persist(newUser);
}
I have verified that the record is in the database at the start of this method. Not sure if this is relevant, but if I do a dao.flush()
at the end of this method I get the following exception:
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException:
Could not execute JDBC batch update
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显然,除非显式或隐式调用刷新(通过查询或提交),否则不会抛出任何潜在的异常。所以我想我必须在所有修改数据的集成测试中调用flush()。
Apparently unless flush is called explicitly or implicitly (via a query or a commit) then any potential exception will not be thrown. So I guess I am going to have to call flush() in all of my integration tests that modify data.
我假设您正在使用事务集成测试?这些测试在每个测试方法结束时回滚,因此您确实错过了刷新。
我不知道这是否有用,但如果您自动生成 ID,那么在 persist() 处会发生刷新,因为需要访问数据库才能获取生成的 ID。但是,如果您分配自己的 ID,那么刷新会延迟到提交为止,正如您所看到的。
I assume you're using the transactional integration tests? These tests rollback at the end of each test method, so you are indeed missing the flush.
I don't know if this is useful, but if you were autogenerating the ID, then a flush would happen at the persist() because a trip to the database is needed to get the generated ID. But if you're assigning your own ID's, then the flush is delayed until the commit, as you've seen.