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 ?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With