Filtering data sets
Sometimes when running DBUnit based tests, not all the data in a table is needed. Only several rows are needed for comparisons in most cases but the entire table should not be cleared because of it.
Fortunately under DBUnit, data sets can be filtered and then compared. Here is an example of setting up a filter with comments:
// Load the actual database table data into a data set IDataSet databaseDataSet = getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable(TABLE_ADDRESS); // Load expected data from an XML dataset ReplacementDataSet expectedDataSet = new ReplacementDataSet( new FlatXmlDataSetBuilder().build(new File("src/test/resources/addressExpected.xml"))); //replace [NULL] strings with null expectedDataSet.addReplacementObject("[NULL]", null); expectedTable = expectedDataSet.getTable(TABLE_ADDRESS); //filter out the columns from the actual dataset by reading the expected //XML file and then using the specified columns to create the dataset. //For this to work, the expected XML dataset MUST be a subset of the //actual dataset and MUST NOT contain columns not present in the actual //dataset. //so this code means that filter the actual table with columns from the //expected table, so if expected table has 3 columns, then in the actual //table, use only those 3 columns ITable filteredColumnsTable = DefaultColumnFilter.includedColumnsTable( actualTable, expectedTable.getTableMetaData().getColumns()); //select a column to scan row data with, if row data matches a value, then use the row IRowFilter rowFilter = new IRowFilter() { @Override public boolean accept(IRowValueProvider rowValueProvider) { Object columnValue = null; try { columnValue = rowValueProvider.getColumnValue("address_line1"); } catch (DataSetException ex) { Logger.getLogger(AddressDaoBeanTest.class.getName()).log(Level.SEVERE, null, ex); } if (((String) columnValue).equalsIgnoreCase("Line1")) { return true; } return false; } }; filteredRowsTable = new RowFilterTable(filteredColumnsTable, rowFilter);
The example is straightforward and filters data from the actual data set obtained from the database and can be used for comparison.
Comparing data set results
To compare results of a unit test run with a data set, use the normal JUnit assert based methods as follows:
// Assert actual database table match expected table Assertion.assertEquals(expectedTable, filteredRowsTable, new Column[]{new Column("address_line3", DataType.VARCHAR)});
This compares results from the actual database data set against the filtered data set using the specified column as a comparator.