Openutils provide a base class that take cares of the common operations involved in preparing the test environment using DbUnit.
You can extend it.openutils.testing.testng.AbstractDbUnitTestNGSpringContextTests or it.openutils.testing.junit.AbstractDbUnitJunitSpringContextTests, depending on the test framework of your choice (remember to include the appropriate dependency, openutils-testing-testng or openutils-testing-junit). Apart from the underline test framework used, there is no difference in how those class will work.
Those base classes extend the standard Abstract*SpringContextTests classes provided by Spring, so they support dependency injection and needs to be configured from a Spring context.
All the setup can be configured using annotations. This is a sample test that can make use of data loaded by DbUnit:
@ContextConfiguration(locations = {"/spring-tests.xml" }) @DbUnitExecution(datasets = {"/db1-load.xml" }) public class SampleDbUnitTest extends AbstractDbUnitTestNGSpringContextTests { @Test public void testSomething() { ... } }
The DbUnitExecution annotation controls how the setup will be performed. It can be configured with a list of file names (xml od xsl DbUnit datasets) that will be loaded before every single method in this test class is executed.
In detail the setup that will be performed before each method is:
You can setup also more than one execution if your tests depend on more than one database or schema, annotating your class like in this example:
@DbUnitConfiguration(dbUnitExecutions = { @DbUnitExecution(datasets = {"/db1-load.xml" }, dataSource = "dataSource1"), @DbUnitExecution(datasets = {"/db2-load.xml" }, dataSource = "dataSource2") })
Note that this test classes don't extend Spring transactional tests, so you need to manually turn on Transactions using standard Spring annotations:
@TestExecutionListeners({TransactionalTestExecutionListener.class }) @Transactional
Also note that the content of your db will definitively be modified by these tests, they are expected to be run on a test-only instance!