Spring Test DBUnit - Table already exists

by GarciaPL on Saturday 16 April 2016

I had a chance to work with Spring Test DBUnit [1] (integration between Spring testing framework and DBUnit) with few tests related with Spring Integration. Most of them use the same common text context which contains embedded database H2. Funny thing was that some tests failed, because of some tables already exist. The issue is that embedded database is not cleared between tests and it is reused within the same context. That's why you should use @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) with @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class}) like below :

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class YourTest {

}




Reference :
[1] Spring Test DBUnit

[2] Spring Framework - DirtiesContext