利用Spring transactionManager进行集成测试

时间:2014-06-17 19:54:28

标签: java spring spring-test

我现在一直在反对这个问题。有一种下沉的感觉我忽略了一些愚蠢的东西。我正在尝试使用事务管理器进行非常简单的集成测试,但似乎无法按照我认为的那样进行回滚。

待测班级:

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上下文(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>

2 个答案:

答案 0 :(得分:1)

如果您使用的是Spring,那么pleeeeease会编写样板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);
    }

}

此致

萨姆

答案 1 :(得分:0)

使用DataSourceUtils.getConnection(dataSource)代替dataSource.getConnection()。前者准备连接以获得事务支持,而后者只是绕过Spring事务基础结构并要求您处理事务详细信息。