【问题标题】:Rollback transaction within test with Spring test使用 Spring 测试在测试中回滚事务
【发布时间】:2015-06-19 01:39:38
【问题描述】:

我试图了解为什么我在测试中抛出异常时无法回滚事务?

我正在使用 Spring 4.1.5,并且正在尝试测试我的交易。 我已经注释了@Transactional 我的存储库和事务已经 如果存储库抛出异常,则回滚。我也注释了 @Transactional 我的测试方法并从 存储库在一个事务中工作。 但是,当我自己在测试中抛出异常时,事务不会回滚。为什么? 看起来是出于某种目的还是我做错了什么?

    @RunWith(SpringJUnit4ClassRunner.class)
    @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
    @ContextHierarchy({
            @ContextConfiguration(locations = {
                    "classpath:/META-INF/spring/jpa-persistence-context.xml"})
    })
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = RuntimeException.class)
    public class FeaturedGroupRepositoryTest2 {

        @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = RuntimeException.class)
        @Test
        public void testFeaturedGroupDao() {

            FeaturedGroupEntity newFeaturedGroupEntity = new FeaturedGroupEntity();
            FeaturedGroupEntity savedFeaturedGroupEntity = featuredGroupRepository.save(newFeaturedGroupEntity);
            FeaturedGroupEntity foundFeaturedGroupEntity = featuredGroupRepository.findOne(savedFeaturedGroupEntity.getId());
            throw new RuntimeException("test rollback");
    }
}

【问题讨论】:

    标签: spring testing


    【解决方案1】:

    可能与@Kieren Dixon 在How to rollback a database transaction when testing services with Spring in JUnit? 中遇到的相同问题是您在 Junit 类上缺少 TransactionalTestExecutionListener 注释:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = TestConfiguration.class)
    @TestExecutionListeners({TransactionalTestExecutionListener.class}) 
    public class WorkUnitRepoTest {
    
        @Inject MyRepo repo;
    
        @Test
        public void test() {
            repo.delete(1);
        }
    }
    

    尽管Spring documentation for 4.1.7 提到默认情况下侦听器处于活动状态,但我必须手动添加它才能工作。然而,@Transactional 在类或方法级别上总是需要它才能工作。

    摘录 Spring Framework 4.1.7.RELEASE:

    在 TestContext 框架中,事务由 TransactionalTestExecutionListener 默认配置, 即使您没有明确声明 @TestExecutionListeners 测试班。但是,要启用对事务的支持,您必须 在 ApplicationContext 中配置一个 PlatformTransactionManager bean 通过 @ContextConfiguration 语义加载(更多细节 下面提供)。此外,您必须声明 Spring 的 @Transactional 注释在您的类或方法级别 测试。

    【讨论】:

      猜你喜欢
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 2017-11-07
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多