Spring Test helpfully rolls back any changes made to the database within a test method. This means that it is not necessary to take the time to delete/reload the test data
One approach that works is to create a "data initialiser" class, add it to a test Spring application context that also has your data source, and wire this application context into your tests. This relies on the fact that Spring caches the application context between test invocations.
For example, a test superclass:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-application-context.xml"})
@Transactional
public abstract class DataLoadingTest {
@Autowired
protected DatabaseInitialiser databaseInitialiser;
}
With test-application-context.xml:
And
public class DatabaseInitialiser extends JdbcDaoSupport {
@PostConstruct
public void load() {
// Initialise your database here: create schema, use DBUnit to load data, etc.
}
}
In this example:
DataLoadingTest;DatabaseInitialiser.load(), via the @PostConstruct annotation;DatabaseInitialiser from the application context, which is already cached;Likewise, DatabaseInitialiser can have a method annotated @PostDestroy to perform any rollback necessary at the end of the whole test run.