Spring Boot : Unit Test with In-Memory Database – Example

If you want to see an minimal example how to use In-Memory database to do unit  test in Spring boot.

This page is for you.

This example is a part of  Spring Boot with all examples

Full Code with Spring Boot 1.5.8.RELEASE:

7_spring-boot-database-jdbi.zip

What you need for run this:

  • Maven 3
  • Java 8
  • Mysql 5.x

What the code will do:

  • Show you how to use In-Memory database with unit  tests

Warning

Explain:

This is the file structure:

In pom.xml you need this:

Line 42 – 54  is Unit test and Mockito.

Line 56 – 61 is h2db which is an In-Memory database.

In UserDaoInMemTest.java

The keys here are:

  • Line 27 : @Spy we are going to “spy” out target class so that we can override the UserDao.getHandle() method
  • Line 34 – 36 : To setup to the In-Memory database
  • Line 39 – 40: To create our table to the database
  • Line 43 : do override to UserDao.getHandle() to return “handle”

Then you do the unit tests like in test_list_ok() and test_insert_ok(). 

  • test_list_ok() : test that we read data correctly by verify that there are 2 rows
  •  test_insert_ok(): test that we can create data by verify that there are 3 rows after call target.insert(userBean)