spring - junit 测试用例事务未提交 - 没有错误

标签 spring jpa junit4 transactional

我们已经在我们的应用程序中实现了 JUnit4,该应用程序使用 Spring 核心和 JPA 以及 DB2。 我们需要测试从一个数据库检索数据并将数据合并到另一个数据库的完整功能。

编写了从第一个数据库检索数据的测试用例,并且运行完美,没有任何错误,但记录没有存储到第二个数据库中。

实现

我们在 TestCase 类中包含了以下注释,以便在必要时使测试用例在事务下运行,

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
      DependencyInjectionTestExecutionListener.class,    
      TransactionalTestExecutionListener.class})
@ContextConfiguration(locations={""})
@TransactionConfiguration(transactionManager="defaultTransactionManager", defaultRollback=false)
@Transactional

在应用程序中,我们有一个管理器类来使用 doSynch() 方法执行此操作。从该方法中,将调用 crudHelper 类的 txStore() 方法来初始化并调用 doStore() 方法(在同一类中)将实体合并到数据库。

以下是整个测试用例逻辑的事务声明

TestCase testSynch() - @Transactional(propagation=Propagation.SUPPORTS)
Manager doSynch() - @Transactional(propagation=Propagation.NEVER)
CRUDHelper txStore() - @Transactional(propagation=Propagation.REQUIRED)
           doStore() - No Transactional annotation

doSynch() 被标记为 NEVER,因为此时它不需要任何事务,并且在进一步的级别(例如在 CRUDHelper 中)可以将事务标记为 REQUIRED 以确保事务可用。

问题

这里,当我们运行调用 Manager 的 doSynch() 方法来测试功能的测试用例时,除了记录未合并且没有抛出错误之外,完整的流程工作正常。

从 JSP 调用 Manager 方法效果很好。 我们还通过直接从测试用例调用 txStore() 进行了测试,它也工作正常。

请告诉我们事务管理是否不当,或者解决此问题会有更大帮助。如果问题或环境不清楚,也请更新我。提前致谢。!!

最佳答案

您是否使用@Rollback注释标记您的方法?

来自JavaDoc :

Test annotation to indicate whether or not the transaction for the annotated test method should be rolled back after the test method has completed. If true, the transaction will be rolled back; otherwise, the transaction will be committed.

关于spring - junit 测试用例事务未提交 - 没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3499857/

相关文章:

Spring 的 DI 不是 transient 的,也不是可序列化的,而是记录 NSE

java - 如何在实体类中添加Map<String, List<String>>?

java - PowerMock 抛出 java.lang.ExceptionInInitializerError

java - Spring 启动 : error ="invalid_grant", error_description ="Bad credentials"

java - Apache Camel Splitter、线程池和 JMS

java - 尝试使用 POST RestTemplate 调用外部 API 时出现 BadRequest 400

java - 我的双向 JPA OneToMany 映射感觉很奇怪

java - 无法跨 EAR 项目形成 EJB 关系。关系属性异常?

java - 加载 native 库的单元测试 Java 类

java - 使用 TestSuite 时,我可以避免在 Eclipse 中运行两次 junit 测试吗?