Spring-test的@Rollback并没有回滚任何东西

时间:2016-11-29 15:19:19

标签: java transactions spring-test

以下工作代码:

//import everything

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Test2.TestConfiguration.class)
@Transactional
public class Test2 {

    @Autowired
    private DataSource datasource;

    @BeforeTransaction
    public void createDatabase() throws SQLException {
        DataSourceUtils .getConnection(datasource)
                        .createStatement()
                        .execute("CREATE TABLE USERS (id bigint, size bigint, primary key (id))");
    }

    @Rollback
    @Test
    public void test() throws SQLException {
        DataSourceUtils .getConnection(datasource)
                        .createStatement()
                        .execute("INSERT INTO USERS VALUES (5, 5)");
    }

    @AfterTransaction
    public void dropTable() throws SQLException {
        ResultSet rs = DataSourceUtils  .getConnection(datasource)
                                        .createStatement()
                                        .executeQuery("SELECT * FROM USERS");
        boolean isEmpty = !rs.next();
        if (isEmpty) {
            System.out.println("Rollback succeeded");
        } else {
            System.out.println("Rollback failed");
        }
        rs.close();

        datasource  .getConnection()
                    .createStatement()
                    .execute("DROP TABLE USERS");
    }

    @Configuration
    public static class TestConfiguration {

        @Bean
        public DataSource driverManagerDataSource() {
            DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
            String dbURI = "database/tests/DerbyDB/db";
            String connectionString = "jdbc:derby:" + dbURI;
            if (!new File(dbURI).exists()) connectionString += ";create=true";
            driverManagerDataSource.setUrl(connectionString);
            driverManagerDataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
            return driverManagerDataSource;
        }

        @Bean
        public PlatformTransactionManager platformTransactionManager() {
            PlatformTransactionManager ptm = new DataSourceTransactionManager(driverManagerDataSource());
            return ptm;
        }
    }
}

解决的问题: 我希望在每次测试后使用@Rollback注释回滚数据库状态。不幸的是,它不起作用。

这是我的测试类:

//import everything

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Test2.TestConfiguration.class)
@Transactional
public class Test2 {

    @Autowired
    private DataSource datasource;

    @BeforeTransaction
    public void createTable() throws SQLException {
        datasource  .getConnection()
                    .createStatement()
                    .execute("CREATE TABLE USERS (id bigint, size bigint, primary key (id))");
    }

    @Rollback
    @Test
    public void test() throws SQLException {
        datasource  .getConnection()
                    .createStatement()
                    .execute("INSERT INTO USERS VALUES (5, 5)");
    }

    @AfterTransaction
    public void dropTable() throws SQLException {
        ResultSet rs = datasource   .getConnection()
                                    .createStatement()
                                    .executeQuery("SELECT * FROM USERS");
        boolean isEmpty = !rs.next();
        if (isEmpty) {
            System.out.println("Rollback succeeded");
        } else {
            System.out.println("Rollback failed");
        }
        rs.close();

        datasource  .getConnection()
                    .createStatement()
                    .execute("DROP TABLE USERS");
    }

    @Configuration
    public static class TestConfiguration {

        @Bean
        public DataSource driverManagerDataSource() {
            DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
            String dbURI = "database/tests/DerbyDB/db";
            String connectionString = "jdbc:derby:" + dbURI;
            if (!new File(dbURI).exists()) connectionString += ";create=true";
            driverManagerDataSource.setUrl(connectionString);
            driverManagerDataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
            return driverManagerDataSource;
        }

        @Bean
        public PlatformTransactionManager platformTransactionManager() {
            PlatformTransactionManager ptm = new DataSourceTransactionManager(driverManagerDataSource());
            return ptm;
        }
    }
}

Spring声称它回滚了数据库,这不是真的,因为记录仍然存在 我如何使它工作?

gru 01, 2016 12:26:14 PM org.springframework.test.context.transaction.TransactionContext startTransaction
INFO: Began transaction (1) for test context [DefaultTestContext@457c9034 testClass = Test2, testInstance = tyvrel.tastas.persistence.Test2@345f69f3, testMethod = test@Test2, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@e15b7e8 testClass = Test2, locations = '{}', classes = '{class tyvrel.tastas.persistence.Test2$TestConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager@3bf9ce3e]; rollback [true]
gru 01, 2016 12:26:14 PM org.springframework.test.context.transaction.TransactionContext endTransaction
INFO: Rolled back transaction for test context [DefaultTestContext@457c9034 testClass = Test2, testInstance = tyvrel.tastas.persistence.Test2@345f69f3, testMethod = test@Test2, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@e15b7e8 testClass = Test2, locations = '{}', classes = '{class tyvrel.tastas.persistence.Test2$TestConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]].
Rollback failed
gru 01, 2016 12:26:14 PM org.springframework.context.support.GenericApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@ae45eb6: startup date [Thu Dec 01 12:26:12 CET 2016]; root of context hierarchy

完整的日志如下:

gru 01, 2016 12:26:12 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
gru 01, 2016 12:26:12 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@69d9c55, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@13a57a3b, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@7ca48474, org.springframework.test.context.support.DirtiesContextTestExecutionListener@337d0578, org.springframework.test.context.transaction.TransactionalTestExecutionListener@59e84876, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@61a485d2]
gru 01, 2016 12:26:12 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@ae45eb6: startup date [Thu Dec 01 12:26:12 CET 2016]; root of context hierarchy
gru 01, 2016 12:26:13 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
gru 01, 2016 12:26:13 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.apache.derby.jdbc.EmbeddedDriver
gru 01, 2016 12:26:14 PM org.springframework.test.context.transaction.TransactionContext startTransaction
INFO: Began transaction (1) for test context [DefaultTestContext@457c9034 testClass = Test2, testInstance = tyvrel.tastas.persistence.Test2@345f69f3, testMethod = test@Test2, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@e15b7e8 testClass = Test2, locations = '{}', classes = '{class tyvrel.tastas.persistence.Test2$TestConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager@3bf9ce3e]; rollback [true]
gru 01, 2016 12:26:14 PM org.springframework.test.context.transaction.TransactionContext endTransaction
INFO: Rolled back transaction for test context [DefaultTestContext@457c9034 testClass = Test2, testInstance = tyvrel.tastas.persistence.Test2@345f69f3, testMethod = test@Test2, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@e15b7e8 testClass = Test2, locations = '{}', classes = '{class tyvrel.tastas.persistence.Test2$TestConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]].
Rollback failed
gru 01, 2016 12:26:14 PM org.springframework.context.support.GenericApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@ae45eb6: startup date [Thu Dec 01 12:26:12 CET 2016]; root of context hierarchy

2 个答案:

答案 0 :(得分:2)

根据我的理解,您将在测试方法中手动创建一个新的独立Spring上下文,该方法在初始化期间创建表。

由于该上下文使用自己的事务管理器和数据源,因此它不会受@Rollback注释的影响 - 在为整个测试类定义的(隐式)spring上下文的上下文中处理该注释。

另请注意,在某些DB中,您无法回滚CREATE命令(但不确定Derby)。

<强>更新

另一个问题是,当您通过datasource.getConnection()建立连接时,实际上并没有使用事务管理器。

来自DataSourceTransactionManager文档:

  

需要应用程序代码才能通过DataSourceUtils.getConnection(DataSource)而不是标准的Java EE样式DataSource.getConnection()调用来检索JDBC连接。诸如JdbcTemplate之类的Spring类隐含地使用了这种策略。

答案 1 :(得分:0)

我认为printTableName()方法中的这一行{{1}}导致了issuse。

关闭连接时会提交事务。

最好使用 entitymanager nextset()来处理交易。