MySQL, Software Development, Spring

Truncate MySQL Tables Before DBUnit Loads Data

This post shows how to truncate a table 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 depends on project requirements. Some projects are okay with this technique, while others are not.

Requirements

Using Spring Test DbUnit

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

The file TestData1.xml contains the data we will load into some MYSQL tables before the @Before, and @Test methods run.

Solution – Truncate Table Before DBUnit Loads Data

The solution is to extend DbUnitTestExecutionListener. Therefore, we need to create a subclass of DbUnitTestExecutionListener. Then, we override the beforeTestMethod method wherein we truncate the table.

Then, the codes delegate calls to the TruncateTablesUtil.truncate(...) method, which looks like the following.

Then, we need to update our unit test as follows.

Note the use of DbUnitTestExecutionListenerX.class in @TestExecutionListeners. Although this is a solution, it is not the best way to meet the objective.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like