29
votes

I have created a Spring web project using Spring Boot. Would like to understand the practice around testing. I require an in memory embedded database say hsql or h2 for my junits with initial schema.sql. And on the main application the database could be say mysql or oracle

In a non Spring Boot project, we would normally have a separate applicationcontext.xml one which is referred by the web app and for testing we would use applicationContext-text.xml

Now, in Spring boot as everything is created automatically and Spring Boot is opiniated too. Would like to know how do I setup having an embedded inmemory db for Junits and an external db like MySQL for the application.

One solution I can think of is using Profiles. with 2 properties file application.properties and application-test.properties. and use test profile for my junits.

Any recommendation on the approach I should take.

1

1 Answers

41
votes

A profile is, indeed, the recommended approach. What I would do is probably make the in-memory implementation the "default" profile (it's harmless, in the sense that you never change any real data, so it's better to make that the default in case someone accidentally runs it against a real database). Personally, I prefer to put all the external configuration in a single application.yml file, but that's really up to you. In the external configuration you need to supply a valid driver class and URL, e.g.

spring:
  datasource:
    driverClassName: org.h2.Driver
    url: jdbc:h2:mem:test;MODE=PostgreSQL
    schema: classpath:/schema.sql

---

spring:
  profiles: local
  datasource:
    url: jdbc:postgresql://localhost/test
    username: root
    password: changeme
    driverClassName: org.postgresql.Driver
    schema:

(Note that H2 has a postgres compatibility mode, so it is really nice as a complement to postgres in production.)