org.dbunit.Assertion Java Examples

The following examples show how to use org.dbunit.Assertion. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DataSourceDBUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenDataSet_whenDelete_thenItemIsDeleted() throws Exception {
    try (InputStream is = DataSourceDBUnitTest.class.getClassLoader()
        .getResourceAsStream("dbunit/items_exp_delete.xml")) {
        // given
        ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS");

        // when
        connection.createStatement().executeUpdate("delete from ITEMS where id = 2");

        // then
        IDataSet databaseDataSet = getConnection().createDataSet();
        ITable actualTable = databaseDataSet.getTable("ITEMS");
        Assertion.assertEquals(expectedTable, actualTable);
    }
}
 
Example #2
Source File: DataSourceDBUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenDataSet_whenInsertUnexpectedData_thenFail() throws Exception {
    try (InputStream is = getClass().getClassLoader()
        .getResourceAsStream("dbunit/expected-multiple-failures.xml")) {

        // given
        IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is);
        ITable expectedTable = expectedDataSet.getTable("ITEMS");
        Connection conn = getDataSource().getConnection();
        DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler();

        // when
        conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')");
        ITable actualData = getConnection().createDataSet().getTable("ITEMS");

        // then
        Assertion.assertEquals(expectedTable, actualData, collectingHandler);
        if (!collectingHandler.getDiffList().isEmpty()) {
            String message = (String) collectingHandler.getDiffList().stream()
                .map(d -> formatDifference((Difference) d)).collect(joining("\n"));
            logger.error(() -> message);
        }
    }
}
 
Example #3
Source File: OldSchoolDbUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenDataSet_whenInsert_thenGetResultsAreStillEqualIfIgnoringColumnsWithDifferentProduced()
    throws Exception {
    String[] excludedColumns = { "id", "produced" };
    try (InputStream is = getClass().getClassLoader()
        .getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) {
        // given
        IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is);
        ITable expectedTable = DefaultColumnFilter
            .excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns);

        // when
        connection.createStatement()
            .executeUpdate("INSERT INTO ITEMS (title, price, produced)  VALUES('Necklace', 199.99, now())");

        // then
        IDataSet databaseDataSet = tester.getConnection().createDataSet();
        ITable actualTable = DefaultColumnFilter
            .excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns);
        Assertion.assertEquals(expectedTable, actualTable);
    }
}
 
Example #4
Source File: DatabaseWriterTest.java    From LicenseScout with Apache License 2.0 5 votes vote down vote up
/**
 * @param expectedDataSet
 * @param databaseDataSet
 * @param tablesNamesToCheck
 * @throws DataSetException
 * @throws DatabaseUnitException
 */
private void checkDatabase(final IDataSet expectedDataSet, final IDataSet databaseDataSet,
                           final List<String> tablesNamesToCheck)
        throws DataSetException, DatabaseUnitException {
    final DefaultColumnFilter columnFilter = createColumnFilter();
    for (final String tableName : tablesNamesToCheck) {
        final ITable actualTable = databaseDataSet.getTable(tableName);
        FilteredTableMetaData metaData = new FilteredTableMetaData(actualTable.getTableMetaData(), columnFilter);
        ITable actualTableFiltered = new CompositeTable(metaData, actualTable);
        final ITable expectedTable = expectedDataSet.getTable(tableName);
        Assertion.assertEquals(expectedTable, actualTableFiltered);
    }
}
 
Example #5
Source File: AbstractDBUnitHibernateMemoryTest.java    From livingdoc-confluence with GNU General Public License v3.0 5 votes vote down vote up
protected void assertTableEquals(Class<?> peristentClass, String[] includedFields, IDataSet dataset) throws Exception {
    // Fetch database data after executing your code
    IDataSet databaseDataSet = getConnection().createDataSet();
    ITable actualTable = databaseDataSet.getTable(getTableName(peristentClass));
    ITable actualData =
        DefaultColumnFilter.includedColumnsTable(actualTable, getColumnNames(peristentClass, includedFields));

    // Load expected data from an XML dataset
    ITable expectedTable = dataset.getTable(getTableName(peristentClass));
    ITable expectedData =
        DefaultColumnFilter.includedColumnsTable(expectedTable, getColumnNames(peristentClass, includedFields));

    // Assert actual database table match expected table
    Assertion.assertEquals(expectedData, actualData);
}
 
Example #6
Source File: EmpireBatchItemDaoTest.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testCreate() throws Exception {
    IDataSet db = database(
            support.loadFlatXmlDataStream(getClass(), "user.xml"),
            support.loadFlatXmlDataStream(getClass(), "batch.xml")
            );
    final IDatabaseConnection dbcon = support.getConnection(tx);
    support.cleanInsert(dbcon, db);
    support.initSequences(tx, 1,
            schema.tableBatchItem.id.getSequenceName()
            );
    tx.commit();

    int batchId = 1;
    BatchItem item = dao.create();
    item.setBatchId(batchId);
    item.setFile("file1.xml");
    item.setLog("log");
    item.setPid("uuid:4a7c2e50-af36-11dd-9643-000d606f5dc6");
    item.setState(ObjectState.LOADED.name());
    item.setType(Type.OBJECT);
    dao.update(item);
    tx.commit();

    ReplacementTable expected = new ReplacementTable(
            support.loadFlatXmlDataStream(getClass(), "batch_item.xml")
                    .getTable(schema.tableBatchItem.getName()));
    expected.addReplacementObject("{$now}", item.getTimestamp());
    Assertion.assertEquals(expected, dbcon.createTable(schema.tableBatchItem.getName()));
}
 
Example #7
Source File: EmpireBatchDaoTest.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testCreate() throws Exception {
    IDataSet db = database(
            support.loadFlatXmlDataStream(getClass(), "user.xml"),
            emptyBatchSet(schema)
            );
    final IDatabaseConnection dbcon = support.getConnection(tx);
    support.cleanInsert(dbcon, db);
    support.initSequences(tx, 1,
            schema.tableBatch.id.getSequenceName());
    tx.commit();

    Batch batch = dao.create();
    batch.setCreate(Timestamp.valueOf("2013-01-17 12:12:12.000"));
    batch.setDevice("device:scanner");
    batch.setEstimateItemNumber(2);
    batch.setFolder("folder/");
    batch.setGenerateIndices(true);
    batch.setLog("log");
    batch.setParentPid("uuid:0eaa6730-9068-11dd-97de-000d606f5dc6");
    batch.setState(State.LOADING);
    batch.setTitle("title_folder/");
    batch.setUserId(1);
    batch.setProfileId(ConfigurationProfile.DEFAULT);
    dao.update(batch);

    tx.commit();

    ReplacementTable expected = new ReplacementTable(
            support.loadFlatXmlDataStream(getClass(), "batch_single_item.xml")
                    .getTable(schema.tableBatch.getName()));

    expected.addReplacementObject("{$now}", batch.getTimestamp());
    Assertion.assertEquals(expected, dbcon.createTable(schema.tableBatch.getName()));
}
 
Example #8
Source File: KylinTestBase.java    From Kylin with Apache License 2.0 5 votes vote down vote up
protected void execAndCompQuery(String queryFolder, String[] exclusiveQuerys, boolean needSort) throws Exception {
    printInfo("---------- test folder: " + queryFolder);
    Set<String> exclusiveSet = buildExclusiveSet(exclusiveQuerys);

    List<File> sqlFiles = getFilesFromFolder(new File(queryFolder), ".sql");
    for (File sqlFile : sqlFiles) {
        String queryName = StringUtils.split(sqlFile.getName(), '.')[0];
        if (exclusiveSet.contains(queryName)) {
            continue;
        }
        String sql = getTextFromFile(sqlFile);

        // execute Kylin
        printInfo("Query Result from Kylin - " + queryName + "  (" + queryFolder + ")");
        IDatabaseConnection kylinConn = new DatabaseConnection(cubeConnection);
        ITable kylinTable = executeQuery(kylinConn, queryName, sql, needSort);

        // execute H2
        printInfo("Query Result from H2 - " + queryName);
        H2Connection h2Conn = new H2Connection(h2Connection, null);
        h2Conn.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new TestH2DataTypeFactory());
        ITable h2Table = executeQuery(h2Conn, queryName, sql, needSort);

        // compare the result
        Assertion.assertEquals(h2Table, kylinTable);

        compQueryCount++;
        if (kylinTable.getRowCount() == 0) {
            zeroResultQueries.add(sql);
        }
    }
}
 
Example #9
Source File: KylinTestBase.java    From Kylin with Apache License 2.0 5 votes vote down vote up
protected void execAndCompDynamicQuery(String queryFolder, String[] exclusiveQuerys, boolean needSort) throws Exception {
    printInfo("---------- test folder: " + queryFolder);
    Set<String> exclusiveSet = buildExclusiveSet(exclusiveQuerys);

    List<File> sqlFiles = getFilesFromFolder(new File(queryFolder), ".sql");
    for (File sqlFile : sqlFiles) {
        String queryName = StringUtils.split(sqlFile.getName(), '.')[0];
        if (exclusiveSet.contains(queryName)) {
            continue;
        }
        String sql = getTextFromFile(sqlFile);
        List<String> parameters = getParameterFromFile(sqlFile);

        // execute Kylin
        printInfo("Query Result from Kylin - " + queryName + "  (" + queryFolder + ")");
        IDatabaseConnection kylinConn = new DatabaseConnection(cubeConnection);
        ITable kylinTable = executeDynamicQuery(kylinConn, queryName, sql, parameters, needSort);

        // execute H2
        printInfo("Query Result from H2 - " + queryName);
        IDatabaseConnection h2Conn = new DatabaseConnection(h2Connection);
        h2Conn.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new TestH2DataTypeFactory());
        ITable h2Table = executeDynamicQuery(h2Conn, queryName, sql, parameters, needSort);

        // compare the result
        Assertion.assertEquals(h2Table, kylinTable);
    }
}
 
Example #10
Source File: DataSourceDBUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenDataSetEmptySchema_whenDataSetCreated_thenTablesAreEqual() throws Exception {
    IDataSet expectedDataSet = getDataSet();
    ITable expectedTable = expectedDataSet.getTable("CLIENTS");
    IDataSet databaseDataSet = getConnection().createDataSet();
    ITable actualTable = databaseDataSet.getTable("CLIENTS");
    Assertion.assertEquals(expectedTable, actualTable);
}
 
Example #11
Source File: DataSourceDBUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception {
    try (InputStream is = DataSourceDBUnitTest.class.getClassLoader()
        .getResourceAsStream("dbunit/items_exp_rename.xml")) {
        // given
        ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS");

        connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");

        IDataSet databaseDataSet = getConnection().createDataSet();
        ITable actualTable = databaseDataSet.getTable("ITEMS");

        Assertion.assertEquals(expectedTable, actualTable);
    }
}