spring - 使用 Spring 测试在测试中回滚事务

标签 spring testing

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

我正在使用 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");
    }
}

最佳答案

可能与@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:

In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener which is configured by default, even if you do not explicitly declare @TestExecutionListeners on your test class. To enable support for transactions, however, you must configure a PlatformTransactionManager bean in the ApplicationContext that is loaded via @ContextConfiguration semantics (further details are provided below). In addition, you must declare Spring’s @Transactional annotation either at the class or method level for your tests.

关于spring - 使用 Spring 测试在测试中回滚事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29610504/

相关文章:

java - 如何使用sqlsession更新mysql

spring - Gradle 构建失败 : Main class name has not been configured and it could not be resolved

java - 在 Mockito 中捕获一个参数

multithreading - 搞乱线程计时的工具?

testing - 是否可以从数据文件传递对象存储库中 HTTP 正文中的动态元素?

java - 在 JUnit 测试期间动态更改 bean 范围

java - 具有多个 JdbcTemplate 和 Spring Boot 的 NoSuchBeanDefinitionException

java - 使用 Spring @Transactionnal,Spring 如何知道使用哪个数据源?

objective-c - 如何创建测试以确保没有保留周期?

iphone - 如何在没有源代码且不使用 iPhone 或 iPad 设备的情况下测试应用程序?