1

我正在使用 DBUnit 来测试我的数据库。我的数据库不是空的,所以我想要的是忽略现有元素并只测试我的测试插入的数据。

这是如何运行测试的示例:

1- 表包含 10 个元素

2- DBUnit 从数据集中插入一些数据(3 个元素)

3-我的测试插入数据(1个元素)

4- 我的预期数据集包含 4 个元素,它们是第一个数据集中定义的 3 个元素和测试最近添加的元素

5-所以,当我对实际表和预期表进行断言时,它会显示一个错误,这是正常的,因为我的表已经包含元素。

问题是:有没有什么办法可以在assert 中忽略数据库中存在的元素?我只想测试数据集插入的数据并进行测试。

这是代码:

@Override
    protected IDataSet getDataSet() throws Exception {
        // transforme fichier XML en BDD
        URL url = this.getClass().getResource("/dataset-peqt2-init.xml");
        File testFile = new File(url.getFile());
        return new FlatXmlDataSetBuilder().build(testFile);
    }



    @Override
    protected DatabaseOperation getSetUpOperation() throws Exception
    {
        return DatabaseOperation.REFRESH;
    }


    /**
     * Reset the state of database 
     * Called before every test
     */
    @Override
    protected DatabaseOperation getTearDownOperation() throws Exception
    {
        return DatabaseOperation.DELETE;
    }


    /**
     * get the actual table from the database
     * @param tableName
     * @return
     * @throws Exception
     * @throws SQLException
     * @throws DataSetException
     */
    private ITable getActualTable(String tableName) throws Exception, SQLException, DataSetException {
        // get the actual table values
        IDatabaseConnection connection = getConnection();
        IDataSet databaseDataSet = connection.createDataSet();
        return databaseDataSet.getTable(tableName);
    }

    /**
     * get the expected table from the dataset
     * @param tableName
     * @param fileName
     * @return
     * @throws Exception
     */
    private ITable getExpectedTable(String tableName, String fileName) throws Exception {
        // get the expected table values
        URL url = this.getClass().getResource("/"+fileName);
        File testFile = new File(url.getFile());
        IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(testFile);
        return expectedDataSet.getTable(tableName);
    }


    @Test 
    public void test01_insert() throws SQLException, Exception {
        File file = new File(SynchroDerbi.class.getResource("/test-insert.lst").getFile());
        log.debug("test01_insert() avec ref : "+file.getName());
        SynchroDerbi.run(file);
        String fileName = "dataset-insert-expected.xml";
        actualTable = getActualTable("equipment");
        expectedTable = getExpectedTable("equipment",fileName);

        Assertion.assertEqualsIgnoreCols(expectedTable, actualTable, new String[]{"id","idSite"});

    }
4

2 回答 2

1

DatabaseOperation.CLEAN_INSERT;getSetUpOperation(). 这样,操作首先将删除所有表记录,然后再插入数据集。

于 2016-11-24T11:42:46.137 回答
0

您的测试不应依赖于系统的当前状态。因此,您应该使用“包含”检查,而不是断言相等。您从 select 获得结果,然后断言这些结果包含您刚刚插入的结果。

如果您想对检查更加严格(这可能会影响测试的可维护性),您可以在之前选择 N 个记录,然后进行插入,然后检查是否 BEFORE+N = AFTER。

PS:DBUnit 不是一个非常灵活和可维护的工具。相反,您可以使用系统代码来保存状态。这样,如果列发生更改 - 您无需更改 DBUnit 数据。为确保您的测试不会相互影响,请使用数据随机化如果您可以在测试中启动和回滚事务,则使用系统代码可能会进一步帮助隔离。

于 2016-11-24T14:10:30.383 回答