Removing H2 in DB memory between integrated tests in maven

I have the following scenario. I have a Hibernate-Spring project that runs on mySQL in production and uses the H2 in-memory DB for integration tests, which is created on the fly. Currently, when I run integration tests with maven, I get errors because the database is maintained between tests. this is unacceptable because I planned that my tests would work on a new database. How to force delete all data in the database between tests? Is there a way to tell maven to omit the circuit and generate it again for each test file?

+4
source share
2 answers

I would look at Spring's embedded database support . You can Spring create and configure a database for you and give you access to it as a simple DataSource . All you really need to do is provide sql scripts to create / populate the database, and the database will be recreated every time it starts.

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

Do not forget the jdbc namespace:

 http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd 
+3
source

How do you conduct integration tests? Spring has built-in support for transactional tests. You can also manually DROP and recreate the database after each test, it is quite simple:

 SCRIPT NOPASSWORDS DROP TO 'file.sql' 

And then restore it with

 RUNSCRIPT FROM 'file.sql' 

I assume that almost every JUnit / TestNG / Fitensse / Selenium / ... testing platform allows you to run some kind of custom code before and after all tests.

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

+1
source

Source: https://habr.com/ru/post/1383125/


All Articles