java-Spring集成测试事务未回滚
作者:互联网
为基于Spring的应用程序编写集成测试遇到事务回滚问题-插入了数据,但是在事务回滚后,数据仍在数据库表中…
Spring 3.0.5,JUnit 4.8.2
集成测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext.xml" })
@TransactionConfiguration(transactionManager="txManager",defaultRollback=true)
@Transactional
public class GenerateCodeStrategyTest {
@Autowired
@Qualifier(value = "generateCodeStrategy")
private Strategy generateCodeStrategy;
@Test
@Transactional
public void genCodeIntegrationTestCommunicationFailure() {
//generate some parameters
SMPPSession mockedSession = mock(SMPPSession.class);
generateCodeStrategy.setSession(mockedSession);
generateCodeStrategy.sendRequest(params);
final SubscribeInfo subscribeInfo = subscribeDao.getUserByPhone(phone);
assertNotNull(subscribeInfo);
assertEquals(phone, subscribeInfo.getPhone());
assertEquals(Status.BAD_STATUS, subscribeInfo.getStatus());
}
}
在日志的调试模式下,我可以看到事务已启动并回滚
INFO: Began transaction (1): transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager@1edd9b3]; rollback [true]
[main] DEBUG org.hibernate.SQL - insert into sms_subscribe (phone_cell, status, ts_subscribe, subscription_status, ts_unsubscribe, receiverIdentification, user_id) values (?, ?, ?, ?, ?, ?, ?)
INFO: Rolled back transaction after test execution for test context [[TestContext@1f18cbe testClass = GenerateCodeStrategyTest, locations = array<String>['classpath:/applicationContext.xml'], testInstance = lv.mrb.server.service.GenerateCodeStrategyTest@14f1726, testMethod = genCodeIntegrationTestCommunicationFailure@GenerateCodeStrategyTest, testException = [null]]]
也许有人知道为什么会这样?谢谢你的帮助.
更新:
该集成测试生成一些参数,然后使用Mockito模拟将会话对象插入到Strategy服务中.该模拟对象只是引发异常,因此在该异常中,Strategy服务数据通过DAO层保存到数据库中.然后通过DAO层测试对数据库的make请求并声明保存的值.
数据是通过Hibernate持久存储的,因此基本上可以这样保存在我的DAO对象中
final Session currentSession = sessionFactory.getCurrentSession();
currentSession.save(object);
sessionFactory是AnnotationSessionFactoryBean,其中数据源是c3p0 ComboPooledDataSource类
更新2:问题出在Mysql引擎上,默认情况下是MyISAM,所以我只需要将其切换到InnoDB,现在一切正常.
解决方法:
常见的问题是您的服务层调用了也标记为@Transactional的其他层,甚至可能使用REQUIRES_NEW.在这种情况下,Test侦听器只能访问外部事务,而无法回滚内部事务.
通常的问题是DAO层上有@Transactional批注.如果有,请将其删除. DAO层上不应有事务划分.
标签:transactions,integration-testing,junit4,spring,java 来源: https://codeday.me/bug/20191102/1993034.html