There is a database-agnostic way to do this if you are using Spring together with Hibernate.
Make sure the application context will be created / destroyed before / after every test method:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:application-context-test.xml"})
@TestExecutionListeners({DirtiesContextTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class})
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public abstract class AbstractTest {
}
Instruct Hibernate to auto create the schema on startup and to drop the schema on shutdown:
hibernate.hbm2ddl.auto = create-drop
Now before every test
- the application context is created and the required spring beans are injected (spring)
- the database structures are created (hibernate)
- the import.sql is executed if present (hibernate)
and after every test
- the application context is destroyed (spring)
- the database schema is dropped (hibernate).
If you are using transactions, you may want to add the TransactionalTestExecutionListener
.