dbunit禁用Oracle约束

时间:2011-01-21 22:43:49

标签: oracle constraints dbunit

我正在使用DbUnit 2.4.8与Oracle 10g和JUnit 4.5。我想在运行DbUnit测试时禁用Oracle中的外键约束,因此我可以独立于所有其他表测试单个表。这就是我到目前为止所做的:

我创建了一个扩展DatabaseTestCase的类(DBUnitHelper)。我已经

@Override
protected IDatabaseConnection getConnection() throws Exception {

    if (usingInternalCtx_)
    {
        if (!esa.util.SysConfig.isRunning())
            esa.util.SysConfig.startupSystem();

        ctx_ = OraPool.getCtx();
    }

    //disable foreign keys
    Connection con = ctx_.getConnection();
    con.prepareStatement("SET CONSTRAINTS ALL DEFERRED").execute();

    return new OracleConnection(con, "my_schema");  // DatabaseConnection(con_);
}

JUnit测试方法是:

@Test
public void useDatabaseTesterToRemoveExistingDataThenRunTest()
{
    IDataSet dataset = null;

    try
    {
        IDatabaseTester databaseTester = dbunit_.getDatabaseTester();
        databaseTester.setDataSet(dbunit_.getDataSet());
        databaseTester.onSetup();   // clean out existing entries in the table specified by the dataset and populate it with entries from the database

        IDataSet databaseDataSet = databaseTester.getDataSet();
        // IDataSet databaseDataSet = con.createDataSet();  // uncomment to retrieve actual rows from the database
        ITable actualTable = databaseDataSet.getTable(TABLE_NAME);

        // Load expected data from an XML dataset
        IDataSet expectedDataSet = dbunit_.getDataSet();
        ITable expectedTable = expectedDataSet.getTable(TABLE_NAME);

        // Assert new testing database table match expected (xml) table
        assertEquals(3,expectedTable.getRowCount());
        assertEquals(expectedTable.getRowCount(), actualTable.getRowCount());
        assertEquals(expectedTable.getValue(1, "oid"), actualTable.getValue(1, "oid"));
        Assertion.assertEquals(expectedTable, actualTable);

        databaseTester.onTearDown();  // by default does nothing
    } catch (Exception e)
    {
        e.printStackTrace();
        fail("test_names has problems");
    }
}

我在Junit专栏上获得ORA-02291: integrity constraint violated - parent key not found errordatabaseTester.onSetup();。当我使用调试器逐步完成此操作时,我发现永远不会调用DBUnitHelper.getConnection()

关于我需要修复什么才能禁用Oracle中的约束?

1 个答案:

答案 0 :(得分:3)

首先要问的是:“您正在处理的表格上的约束是否被创建为DEFERRABLE?”

您可以通过发出以下查询来检查:

SELECT constraint_name, table_name, DEFERRABLE 
  FROM all_constraints 
 WHERE owner = 'myschema'
   AND table_name = 'THE_TABLE';

如果约束没有创建为DEFERRABLE,则命令SET ALL CONSTRAINTS DEFERRED基本上没有效果。

如果约束不可延迟,则必须将其删除并重新创建为可延迟。您无法将其修改为可延迟。