我想了解为什么我在测试中抛出异常时无法回滚事务?
我正在使用 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/