To keep the independency between the JUnit tests, I need to create the database at the beginning of every test, and destroy it at the end of every test.
The database
You should probably use JPA or Spring features, but just for completeness:
On the database side, H2 supports running init scripts when opening the database as follows:
jdbc:h2:mem:test;INIT=runscript from '~/create.sql'
or
jdbc:h2:mem:test;INIT=runscript from 'classpath:/com/acme/create.sql'
And when you close in-memory databases (like the example above), the data is dropped. Or you could run the SQL statement drop all objects.
JPA2.1 supports drop-and-create of schema when the EMF is initialised.
You should be able to use Spring's embedded database configuration to specify an H2 datasource (also shown here):
<jdbc:embedded-database id="dataSource" type="H2">
<!-- Modify locations appropriately for your environment -->
<jdbc:script location="classpath:db-schema.sql"/>
<jdbc:script location="classpath:db-test-data.sql"/>
</jdbc:embedded-database>
That should go in your test-specific testApplicationContext.xml
with the appropriate namespace declarations.
Spring will create the H2 datasource when it brings up the test application context at the beginning of the test suite (test class). Because Spring caches the application context for the duration of the test class, you can annotate the test class with @DirtiesContext
so that the application context is re-created and datasource re-initialized for each test method:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/your/testApplicationContext.xml"})
@DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD)
public class SomeDatabaseTest {
@Autowired
private SomeDao dao;
// Test methods
}
More info on Spring's embedded database functionality can be found here