强制“重新加载” JPA EntityManager在集成测试中的应用
在启用 Spring 的集成测试中,我需要强制 EntityManager 从数据库中重新读取。
@Test
@DataSet("/xml/dbunit/truncate-tables.xml")
public void createTerminalFromQuery() {
// there should be zero terminals in the empty database
Assert.assertEquals(0, terminalService.countTerminals());
// makes remote REST call updating database outside the application's EntityManager
HttpEntity<QueryResponse> result = simulateRequest("query");
// attempts to force re-read of updated database (unsuccessfully)
entityManagerService.getEntityManager().flush();
// there should be exactly one Terminal in the database
Assert.assertTrue(terminalService.existsTerminalBySerialNumber(EXISTING_TERMINAL_SERIAL_NUMBER));
}
已验证终端已创建并存在于数据库中。尽管如此,第二个断言还是失败了。当第一个断言被注释掉时,第二个断言就可以了。
测试框架是Unitils/DBUnit,通过@PersistenceContext注入EntityManager很困难,因为所需的包unitils-orm依赖于Spring 2.5和JPA 1.0,从而导致其他问题。
相反,我创建了 EntityManagerService 并验证它确实使用与 TerminalService 相同的 EntityManager。
我已经尝试过EntityManager.clear()和flush()并从EntityManagerFactory中逐出缓存 - 但似乎没有任何效果。
有什么建议吗?
In a Spring-enabled integration test, I need to force the EntityManager to re-read from the database.
@Test
@DataSet("/xml/dbunit/truncate-tables.xml")
public void createTerminalFromQuery() {
// there should be zero terminals in the empty database
Assert.assertEquals(0, terminalService.countTerminals());
// makes remote REST call updating database outside the application's EntityManager
HttpEntity<QueryResponse> result = simulateRequest("query");
// attempts to force re-read of updated database (unsuccessfully)
entityManagerService.getEntityManager().flush();
// there should be exactly one Terminal in the database
Assert.assertTrue(terminalService.existsTerminalBySerialNumber(EXISTING_TERMINAL_SERIAL_NUMBER));
}
It has been verified that the Terminal is created and exists in the database. Despite this, the second assertion fails. When the first assertion is commented out, the second one is OK.
The test framework is Unitils/DBUnit and injecting an EntityManager via @PersistenceContext is difficult, as the required package unitils-orm depends on Spring 2.5 and JPA 1.0 leading to other problems.
Instead, I have created the EntityManagerService and verified that it indeed uses the same EntityManager as the TerminalService.
I have tried EntityManager.clear() and flush() and evicting the Cache from the EntityManagerFactory - but nothing seems to have any effect.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
目前尚不清楚如何管理交易。由于
clear()
没有帮助,可能这两项检查都是在同一个事务内执行的,而该事务看不到 REST 服务提交的事务的结果。尝试在不同的事务中执行检查。
It's not clear how do you manage transactions. Since
clear()
doesn't help, perhaps both checks are executed inside the same transaction that doesn't see result of the transaction committed by the REST service.Try to execute checks in different transactions.