Spring + JUnit + H2 + JPA : Is it possible to drop-create the database for every test?

16,112

Solution 1

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

Solution 2

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.

Share:
16,112
Admin
Author by

Admin

Updated on July 22, 2022

Comments

  • Admin
    Admin almost 2 years

    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 should be created in memory ( H2 database ) by executing SQL queries that exist in a SQL file (Native insert queries...).

    Defining my keys-values in a properties file and respecting JPA specification (persistence.xml), how can I create-drop database for every JUnit test using annotations/injections?

    Thank you a lot!