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] ?
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.
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")
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With