在Spring中配置特定的内存数据库以进行测试 [英] Configure specific in memory database for testing purpose in Spring

查看:82
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆