07.13.2016 | Steffen Mall | comment icon 0 Comment

Best practice in order to integrate liquibase in JUnit – using hibernate JPA with in memory h2 database combined with mockito

In addition to my first liquibase post “basics of continuous database integration with liquibase” I give you some best practice in order to

  • integrate liquibase in junit – using hibernate JPA with in memory h2 database
  • use mockito to inject the entity manager in a JUnit test

Execute liquibase db.changelog.xml with hibernate JPA and h2 in memory database

Let us start with a simple JUnit test to test our db.changelog.xml file with hibernate JPA entitymanager.

If you don´t have a db.changelog.xml file in your project, just add an example db.changelog.xml.

In our JUnit test we use an in memory h2 database and hibernate JPA. Therefore, just add these dependencies to your pom.xml.

Afterwards create your persistence.xml in your test folder (src\test\resources\META-INF). Using h2 in memory database – the connection url looks like jdbc:h2:mem:your-test-db;DB_CLOSE_DELAY=-1;MVCC=true. H2 database store the data In-Memory, this is useful to build and teardown easily a temporary database.

Finally create a JUnit test and execute the liquibase file. To get an instance of liquibase you need an instance of liquibase.database.Database and the database needs a java.sql.Connection. For this reason you need to create an instance of the entity manager to get this connetction e.g.:

After this use the hibernate session to get the connection e.g.:

Finally get an instance of liquibase database and liquibase instance to execute the db.changelog.xml. Execute the db.changlog.xml and drop database after the test e.g.:

Everything is fine and your db.changelog.xml is tested and ready for other stages. With this simple test you are able to verify the validity of your liquibase file without starting your application server. Additional you can use the trick to setup your database as a base of other test cases.

Additional tip to integrate liquibase using mockito

If you have already integrated JPA tests in your JUnit test landscape – do not use auto ddl in JUnit and liquibase in your live project. You can also use your real db.changelog.xml to setup your test database. In my short example I will use the power of mockito to inject the entitymanager into the example DAO. Setup the database via liquibase db.changelog.xml, use the DAO to execute some database operation or something else. Feel free to implement your abstraction according to your test landscape.

 

java ee jpa junit liquibase mockito

Leave a Comment