利用Spring transactionManager进行集成测试



我已经纠结了一段时间了&我有种不祥的预感,我忽视了一些愚蠢的事情。我试图使用一个事务管理器进行一个非常简单的集成测试,但似乎不能让它回滚,因为我认为它应该。

待测类:

public class JdbcUserDAO implements UserDAO {
@Autowired
private DataSource dataSource;
private static final String TERM_USER_SQL =
        "UPDATE USER " +
        "SET TERM_DATE = date('now') " +
        "WHERE USER_NAME = ?";
@Override
public void terminateUser(String userName) {
    try (Connection conn = dataSource.getConnection()){
        PreparedStatement stmt = conn.prepareStatement(TERM_USER_SQL);
        stmt.setString(1, userName);
        stmt.executeUpdate();
    } catch (SQLException e) {
        throw new RuntimeException("Caught SQLException in persistence service", e);
    }
}

Spring context (applicationContext.xml):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
                       http://www.springframework.org/schema/beans/spring-beans.xsd
                       http://www.springframework.org/schema/tx
                       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<tx:annotation-driven/>
<bean id="userDAO" class="com.mycompany.persistence.dao.impl.JdbcUserDAO"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.sqlite.JDBC"/>
    <property name="url" value="jdbc:sqlite:C:\development.sqlite3"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})
@TransactionConfiguration
@Transactional
public class JdbcUserDAOTest {
    @Autowired
    private UserDAO userDAO;
    @Test
    public void test_terminateUser() {
        userDAO.terminateUser("USERNAME");
    }
}

AFAIK, TransactionConfiguration的defaultRollback行为是"true",默认的transactionManager bean名称是"transactionManager",所以我应该设置在那里。我运行这个测试,并期望"TERM_DATE"列在测试完成后恢复为"null"(其起始值),但它不是(我在测试完成后查询,可以看到它仍然是=今天的日期)。

我甚至得到了看起来非常有希望的日志记录:

Jun 17, 2014 1:25:48 PM org.springframework.test.context.transaction.TransactionalTestExecutionListener startNewTransaction
INFO: Began transaction (1): transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager@10279954]; rollback [true]
Jun 17, 2014 1:25:48 PM org.springframework.test.context.transaction.TransactionalTestExecutionListener endTransaction
INFO: Rolled back transaction after test execution for test context [TestContext@41cbd50f testClass = JdbcUserDAOTest, testInstance = com.mycompany.persistence.dao.JdbcUserDAOTest@2d10ed88, testMethod = test_terminateUser@JdbcUserDAOTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@325a92d5 testClass = JdbcUserDAOTest, locations = '{classpath:/applicationContext.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
Jun 17, 2014 1:25:48 PM org.springframework.context.support.GenericApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@3304e92a: startup date [Tue Jun 17 13:25:48 MDT 2014]; root of context hierarchy
我到底忽略了什么?提前感谢。

如果有帮助,相关的POM依赖项如下:

<dependencies>
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.7.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-core</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>3.2.9.RELEASE</spring.version>
</properties>

如果您正在使用Spring,请写而不是编写样板JDBC代码。

应该使用Spring的JdbcTemplate,它可以自动处理当前Spring管理的事务,并且可以消除所有样板JDBC代码。

你应该用这样的东西替换你的整个DAO实现:

public class JdbcUserDAO {
    private static final String TERM_USER_SQL = "UPDATE USER "
            + "SET TERM_DATE = date('now') WHERE USER_NAME = ?";
    private final JdbcTemplate jdbcTemplate;
    @Autowired
    public JdbcUserDAO(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
    public void terminateUser(String userName) {
        jdbcTemplate.update(TERM_USER_SQL, userName);
    }
}

问候,山姆

DataSourceUtils.getConnection(dataSource)代替dataSource.getConnection()。前者为事务支持准备连接,而后者只是绕过Spring事务基础设施,并要求您处理事务细节。

相关内容

  • 没有找到相关文章

最新更新