Skip to content
Advertisement

Use a secondary h2 database for testing an API in Spring boot

I’m developing an API to manage a database in the company where I work, the problem is that when I have to run the different test I have to use the “real” dev database (in h2) where I have some real data.

I thought about it and what I wanted to do is create a new h2 database that could start in the testing phase, and use it to test all my Controller methods.

The problem is that I have no clue of how to achieve this in Spring Boot. If you could help me I’d be very grateful.

To sum it up:

  • I have an h2 database
  • I want to use a secondary h2 for testing
  • How coul I achieve this?

Thanks!

Advertisement

Answer

Let us assume you have 2 environments – “production” and “testing”.

Step 1: Define one configuration file for each environment

Keep one application.properties files for each environment. Each will contain its own settings for the database. Like this:

Production: application-production.properties

#Start: For MySQL 8.0 database.
spring.datasource.url= jdbc:mysql://${DB_IP}:${DB_PORT}/${DB_SCHEMA}
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASSWD}
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect
#End: For MySQL 8.0 database.

spring.sql.init.platform=mysql

Testing: application-testing.properties

# Start: For H2 in-memory database.
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=secret
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
# End: For H2 in-memory database.

spring.sql.init.platform=h2

Step 2: Build your application bootable JAR

There is nothing to explain here. 🙂

Step 3: Pass the profile name when running the JAR

  • For testing environment: $ java -jar -Dspring.profiles.active=testing <spring-boot-application-jar>
  • For production environment: $ java -jar -Dspring.profiles.active=production <spring-boot-application-jar>

The first one will use application-testing.properties and the second one application-production.properties.

There are some other factors too like default properties in application.properties and the specific ones in profile-based properties, etc. which you may read up on the Spring docs.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement