DbUnit – Truncate all Tables in MySQL before Data are loaded via @DatabaseSetup

This post is about truncating all tables in a MySQL database before DbUnit loads data via @DatabaseSetup. Doing it in @Before method does not work. 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. Basically, we need to use DbUnitTestExecutionListener to be able to us its annotations like @DatabaseSetup.

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


Extend DbUnitTestExecutionListener

We need to created a subclass of DbUnitTestExecutionListener

The codes delegate calls 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.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert