该对象已在集成测试中关闭

时间:2016-12-23 12:29:10

标签: java dbunit spring-test-dbunit

我正在使用spring-test-dbunit来运行集成测试。我想在一个类中使用不同的数据集。

我有BaseRepositoryTest课程

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = {
        "classpath:path/to/context/context.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
@TransactionConfiguration()
public abstract class BaseRepositoryTest extends AbstractTransactionalJUnit4SpringContextTests {
    /** Database connection. */
    @Autowired
    protected IDatabaseConnection databaseConnection;


    /**
     * Configures database connection.
     */
    @PostConstruct
    public void initConfig() {
        try {
            databaseConnection.getConnection().setAutoCommit(true);
        } catch (SQLException e) {
            // throws exception
        }
    }

    /**
     * Load dataset data.
     *
     * @param datasetPath path to dataset
     */
    protected void loadData(String datasetPath) {
        try {
            IDataSet dataset = new FlatXmlDataSetBuilder()
                    .setColumnSensing(true)
                    .build(new ClassPathResource(datasetPath).getFile());
            DatabaseOperation.CLEAN_INSERT.execute(databaseConnection, dataset);
        } catch (Exception e) {
            // throws exception
        }
    }

BaseAnnotatedRepositoryTest

@DbUnitConfiguration(databaseConnection = { "databaseConnection" })
@TestExecutionListeners(DbUnitTestExecutionListener.class)
public abstract class BaseAnnotatedRepositoryTest extends BaseRepositoryTest {

这是测试

public class PrototypeTest extends BaseAnnotatedRepositoryTest {

    private static final String TEST_DATASET =
            "testDataset.xml";

    @Autowired
    private IQuestionRepository repository;

    @Test
    @DatabaseSetup(TEST_DATASET)
    public void testSimple() {
    }

    @Test
    @DatabaseSetup(TEST_DATASET)
    public void anotherTestSimple() {
    }

}

当我尝试运行测试时,我得到了该原因的错误

org.h2.jdbc.JdbcSQLException: The object is already closed [90007-170]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
    at org.h2.message.DbException.get(DbException.java:169)
    at org.h2.message.DbException.get(DbException.java:146)
    at org.h2.message.DbException.get(DbException.java:135)
    at org.h2.jdbc.JdbcConnection.checkClosed(JdbcConnection.java:1388)
    at org.h2.jdbc.JdbcConnection.checkClosed(JdbcConnection.java:1366)
    at org.h2.jdbc.JdbcConnection.setAutoCommit(JdbcConnection.java:406)

如果我将这些测试方法分开 - 例如将每个方法移动到它自己的类 - 它可以正常工作。

1 个答案:

答案 0 :(得分:0)

当我将AFTER_CLASS更改为AFTER_EACH_TEST_METHOD时,它开始正常工作。 (虽然时间大大增加)