Skip to content

Create a database test case

Grigorios Avgitidis edited this page Jan 13, 2015 · 3 revisions

This project makes use of the DbUnit framework, for test cases that need a known state database instance between test runs.

Enable DbUnit testing

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.

Hints for extending DBTestCase

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 file, contains the test schema, with data we will be inserting in our dataset before every 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.

WARNING

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!

Clone this wiki locally