-
Notifications
You must be signed in to change notification settings - Fork 6
Create a database test case
This project makes use of the DbUnit framework, for test cases that need a known state database instance between test runs.
Currently, there are two (2) ways to create a DbUnit test case in this project:
- Through extending
DBTestCase
This is the framework's recommended way of creating database unit tests from scratch. For more information check the DbUnit getting started guide.
- Through extending
BaseDbUnitTestCase
BaseDbUnitTestCase
, is an abstracted implementation of DBTestCase
. It serves as a base test case, properly configured with @ActiveProfiles("test")
annotation, in order to force all inherited tests to run with configurations for test profile, defined in test resources. Also, with the use of @TransactionConfiguration(defaultRollback = true)
annotation, it ensures that transactions with database will safely rollback after the test run.
The on test DataSource (db) must be injected into the test case (through spring context).
getDataSet()
method, must be overwritten and implemented as follows:
@Override
protected IDataSet getDataSet() throws Exception {
return new FlatXmlDataSetBuilder().build(new FileInputStream("src/test/resources/Dbunit/testdb.xml"));
}
myTestData.xml, contains the datasource, that would be inserted in the dataset before each test
Then we have to make JUnit insert data in our dataset before each test, by implementing setUp()
as follows:
@Before
public void setUp() throws Exception {
IDatabaseConnection connection = new DatabaseDataSourceConnection(dataSource);
DatabaseOperation.CLEAN_INSERT.execute(connection, getDataSet());
}
Implementing the
tearDown()
method is not necessary.
If an item is inserted manually, let's say, by calling repository's save()
method, thus incrementing the id,
the latter will be "consumed". Those will be reset after the test run, when the transaction rollback takes place.
Tests run on HSQLDB (in-memory database) while the main part is independent from this "test" configuration.
Happy testing!