在 Spring 中配置特定的内存数据库以用于测试目的 [英] Configure specific in memory database for testing purpose in Spring
问题描述
如何配置我的 Spring Boot 应用程序,以便在我运行单元测试时它将使用内存数据库,例如 H2/HSQL,但当我运行 Spring Boot 应用程序时,它将使用生产数据库 [Postgre/MySQL]?
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] ?
推荐答案
可以使用 Spring 配置文件.这将是一种特定的方式:
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
在 pom.xml
中有 MySQL 和 H2 驱动程序,像这样:
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>
最后但并非最不重要的一点是,使用 @ActiveProfiles("test")
注释测试类.
Last but not the least, annotate Test classes with @ActiveProfiles("test")
.
这篇关于在 Spring 中配置特定的内存数据库以用于测试目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!