Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping H2 in memory DB between integeration tests in maven

Tags:

spring

maven

h2

I have the following scenario. I have an Hibernate-Spring Project, which works on mySQL on production, and uses H2 in-memory DB for integration tests, which is created on-the-fly. Currently, when I run the integeration tests with maven, I get errors, because the database is maintained between the tests. this is unacceptable, because I planned my tests to run on a fresh DB. How do I force the deletion of all data in the DB between the tests ? Is there a way to tell maven to drop the schema and generate it again for each test file ?

like image 248
stdcall Avatar asked Oct 10 '22 09:10

stdcall


2 Answers

I would take a look at Spring's support for embedded databases. You can let Spring do the database creation and setup for you and provide you access to it as a simple DataSource. All you really need to do is provide the sql scripts to create/populate the database, and with each run, the database will be re-created.

<jdbc:embedded-database id="dataSource" type="h2">
    <jdbc:script location="classpath:schema.sql"/>
    <jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>

Don't forget the jdbc namespace:

http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
like image 103
nicholas.hauschild Avatar answered Oct 13 '22 11:10

nicholas.hauschild


How are you running the integration tests? Spring has a built-in support for transactional tests. Also you can manually DROP and recreate the database after each test, this is pretty simple:

SCRIPT NOPASSWORDS DROP TO 'file.sql'

And then restore it with:

RUNSCRIPT FROM 'file.sql'

I guess virtually every testing framework JUnit/TestNG/Fitensse/Selenium/... allows to run some custom code before all tests and after each and every.

Here is my blog post explaining how it works and an example setup for ScalaTest.

like image 27
Tomasz Nurkiewicz Avatar answered Oct 13 '22 11:10

Tomasz Nurkiewicz