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

StackOverflow https://stackoverflow.com/questions/21246802

  •  30-09-2022
  •  | 
  •  

質問

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!

役に立ちましたか?

解決

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

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top