我尝试为我的 dao 层设置一个 Junit 测试用例。但是,我不希望测试数据实际保存到数据库中。
所以我认为我应该在每次测试后进行事务处理并回滚。这给我留下了以下数据源设置:
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
p:driverClass="org.postgresql.Driver"
p:jdbcUrl="jdbc:postgresql://***"
p:user="***"
p:password="***/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:packagesToScan="***"
p:hibernateProperties-ref="hibernateProps" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:dataSource-ref="dataSource"
p:sessionFactory-ref="sessionFactory"/>
待测dao类设置如下:
@Repository
@Transactional
@SuppressWarnings("unchecked")
public class BallotBoxRepositoryHibernateImpl implements BallotBoxRepository {
@Autowired
private SessionFactory sessionFactory;
@Override
public void saveVote(DaoObject v) {
Session sess = sessionFactory.openSession();
sess.beginTransaction();
sess.save(v);
sess.getTransaction().commit();
sess.close();
}
[...]
}
实际的持久化工作确实工作得很好。但是,从未进行预期的回滚:
INFO main transaction.TransactionalTestExecutionListener:292 - Rolled back transaction after test execution for test context [...]
TransactionalTextExecutionListener 定义如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/applicationContext.xml"})
@TestExecutionListeners({WebTestExecutionerListener.class, DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class DaoTest { ... }
我正在使用自动装配的成员来访问我的 dao 方法:
@Autowired
private BallotBoxRepository repo;
TL;博士
JUnit 测试用例会保留测试数据,即使它表明已完成回滚。