如何回滚测试

hud*_*udi 5 java spring

这是我的测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:repositoryContextTest.xml" })
@Transactional
@TransactionConfiguration(defaultRollback = true)
public class SeasonITest {
@Autowired
private SeasonDao seasonDao;

@Test
public void createSeason() throws Exception {
    Season season = new Season();
    season.setName("2012");
    seasonDao.createSeason(season);
}
Run Code Online (Sandbox Code Playgroud)

和我的bean配置文件中的dataSource

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/tournament_system" />
    <property name="username" value="root" />
    <property name="password" value="root" />
    <property name="defaultAutoCommit" value="false"/>
    <property name="poolPreparedStatements" value="false"/>
    <property name="maxOpenPreparedStatements" value="0"/>
 </bean>

<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
Run Code Online (Sandbox Code Playgroud)

当我运行此测试时,会在我的数据库中创建一条新记录.

我该如何回滚此交易?

这是我看到的日志输出:

2012-06-15 15:00:02,173 [main] INFO  - ionalTestExecutionListener - 
 Rolled back transaction after test execution for test context 
 [[TestContext@76db09 testClass = SeasonITest, 
   locations = array<String>['classpath:repositoryContextTest.xml'], 
   testInstance = org.toursys.repository.dao.SeasonITest@1265109, 
   testMethod = createSeason@SeasonITest, testException = [null]]]
Run Code Online (Sandbox Code Playgroud)

更新:

以下所有答案都想改变我不想要的逻辑或数据库引擎.所以我提供的声誉指向正确的答案:

为什么我这样做: @TransactionConfiguration(defaultRollback = true)在事务配置测试中没有回滚以及如何修复它?

Kry*_*ber 7

如果你使用MySQL和MyISAM引擎尝试切换到InnoDB.

对于更复杂的测试,您可能需要一个模拟框架或DB娱乐.

编辑1:根据文档,InnoDB是完全ACID支持的事务,而MyISAM支持原子操作.更多阅读:交易和原子操作的差异

EDIT2:在@TransactionConfiguration中,defaultRollback的默认值为true,因此您应该添加@TransactionConfiguration(defaultRollback = false),而不是注释该行.