9

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!

  • I have the described arrangement working with Arquillian, but using JBoss 7.1.1 instead of Spring and Hibernate as JPA impl. If you can you use Arquillian with Spring, let me know. – kostja Jan 21 '14 at 07:54

3 Answers3

26

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

Community
  • 1
  • 1
Will Keeling
  • 22,055
  • 4
  • 51
  • 61
3

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.

Thomas Mueller
  • 48,905
  • 14
  • 116
  • 132
-1

JPA2.1 supports drop-and-create of schema when the EMF is initialised.

DataNucleus
  • 15,497
  • 3
  • 32
  • 37