MySQL, Software Development

Truncate MySQL Tables Before DBUnit Loads Data

This post is about truncating tables in MySQL before DbUnit loads data via @DatabaseSetup. Truncating the tables in the @Before method does not work because DBUnit loads the data first via @DatabaseSetup before delegating calls to a @Before method. Please be advised that it may be a bad idea to truncate all tables for each @Test method. However, it really depends on project constraints.


  • DbUnit 2.5.4
  • MySQL
  • Spring Boot 1.5.10.RELEASE
  • Sprint Test DbUnit 1.2.1

Using Spring Test DbUnit

Using Spring Test DbUnit is straight-forward. We use DbUnitTestExecutionListener to be able to use its annotations like @DatabaseSetup.

The file TestData1.xml contains the data to be loaded into some MYSQL tables before @Before and @Test methods are run.


Extend DbUnitTestExecutionListener

We need to create a subclass of DbUnitTestExecutionListener

The codes delegate calls to TruncateTablesUtil.truncate(…) method which looks something this:

Use the subclass

We then need to update our unit test.

Note the use of DbUnitTestExecutionListenerX.class in @TestExecutionListeners.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like