Skip to content

Instantly share code, notes, and snippets.

@andrewspencer
Created December 17, 2010 10:46
Show Gist options
  • Save andrewspencer/744769 to your computer and use it in GitHub Desktop.
Save andrewspencer/744769 to your computer and use it in GitHub Desktop.
EqualDataSetAssertBuilder: a wrapper around DbUnitAssert.assertEqualsIgnoreCols(), DBUnit's post-test dataset equality assertion, to allow comparing multiple tables instead of just one table at a time.
import java.util.HashMap;
import java.util.Map;
import org.dbunit.DatabaseUnitException;
import org.dbunit.assertion.DbUnitAssert;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.filter.DefaultColumnFilter;
/**
* Builder for an assertion of equality between two instances of IDataSet,
* by listing the tables to compare and optionally the columns to ignore
* for each table. (Based upon DbUnitAssert.assertEqualsIgnoreCols() but
* extended to a complete IDataSet rather than limiting the comparison to
* a single table.)
*
* @author Andrew Spencer
*/
public final class EqualDataSetAssertBuilder {
protected DbUnitAssert dbUnitAssert = new DbUnitAssert();
private Map<String, AssertTable> tablesToAssertByName = new HashMap<String, AssertTable>();
protected IDataSet expectedDataSet;
protected IDataSet actualDataSet;
public static EqualDataSetAssertBuilder getBuilder(IDataSet expectedDataSet, IDataSet actualDataSet) {
return new EqualDataSetAssertBuilder(expectedDataSet, actualDataSet);
}
private EqualDataSetAssertBuilder(IDataSet expectedDataSet, IDataSet actualDataSet) {
this.expectedDataSet = expectedDataSet;
this.actualDataSet = actualDataSet;
}
public EqualDataSetAssertBuilder addTable(String tableName, String... ignoreCols) {
tablesToAssertByName.put(tableName, new AssertTable(tableName, ignoreCols));
return this;
}
public void assertDatabaseDataMatchExpectedData() throws DatabaseUnitException {
for (AssertTable tableToAssert : tablesToAssertByName.values()) {
tableToAssert.doAssert();
}
}
private class AssertTable {
private String tableName;
private String[] ignoreCols;
public AssertTable(String tableName, String[] ignoreCols) {
this.tableName = tableName;
this.ignoreCols = ignoreCols;
}
public void doAssert() throws DatabaseUnitException {
ITable expectedTable = expectedDataSet.getTable(tableName);
final ITable expectedTableFiltered = DefaultColumnFilter
.excludedColumnsTable(expectedTable, ignoreCols);
ITable actualTable = actualDataSet.getTable(tableName);
final ITable actualTableFiltered = DefaultColumnFilter
.excludedColumnsTable(actualTable, ignoreCols);
new DbUnitAssert().assertEqualsIgnoreCols(expectedTableFiltered, actualTableFiltered, ignoreCols);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment