Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure specific in memory database for testing purpose in Spring

How do I configure my Spring Boot application so that when I run unit tests it will use in-memory database such as H2/HSQL but when I run Spring Boot application it will use production database [Postgre/MySQL] ?

like image 861
IllSc Avatar asked Aug 14 '15 02:08

IllSc


People also ask

Should I use in-memory database for testing?

This database provider allows Entity Framework Core to be used with an in-memory database. While some users use the in-memory database for testing, this is generally discouraged; the SQLite provider in in-memory mode is a more appropriate test replacement for relational databases.


2 Answers

Spring profiles can be used for this. This would be a specific way:

Have environment specific properties files:

application.properties:

spring.profiles.active: dev 

application-dev.properties

spring.jpa.database: MYSQL spring.jpa.hibernate.ddl-auto: update  spring.datasource.url: jdbc:mysql://localhost:3306/dbname spring.datasource.username: username spring.datasource.password: password 

application-test.properties

spring.jpa.database: HSQL 

Have both MySQL and H2 drivers in pom.xml, like this:

<dependency>     <groupId>mysql</groupId>     <artifactId>mysql-connector-java</artifactId>     <scope>runtime</scope> </dependency>  <dependency>     <groupId>org.hsqldb</groupId>     <artifactId>hsqldb</artifactId>     <scope>test</scope> </dependency> 

Last but not the least, annotate Test classes with @ActiveProfiles("test").

like image 124
Sanjay Avatar answered Sep 20 '22 05:09

Sanjay


Another approach is to add the annotation @AutoConfigureTestDatabase to you test class. My tests usually look like this:

@RunWith(SpringRunner.class) @DataJpaTest @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2) public class MyRepositoryTest {      @Autowired     MyRepository repository;      @Test     public void test() throws Exception {         // Tests...     } } 

Note that the embedded database dependency needs to be added in the pom.xml file. For embedded database this annotation is not necessary it will work even if only the dependency is added in pom file.

like image 30
ronhash Avatar answered Sep 20 '22 05:09

ronhash