在内存数据库中配置特定的内存数据库以在 Spring 中进行测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32001391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Configure specific in memory database for testing purpose in Spring
提问by IllSc
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 Boot 应用程序,以便在运行单元测试时使用内存数据库,例如 H2/HSQL,但是当我运行 Spring Boot 应用程序时,它将使用生产数据库 [Postgre/MySQL]?
回答by Sanjay
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
应用程序-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
application-test.properties
spring.jpa.database: HSQL
Have both MySQLand H2drivers in pom.xml
, like this:
在 中有MySQL和H2驱动程序pom.xml
,如下所示:
<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")
.
最后但并非最不重要的一点是,用@ActiveProfiles("test")
.
回答by ronhash
Another approach is to add the annotation @AutoConfigureTestDatabase
to you test class.
My tests usually look like this:
另一种方法是将注释添加@AutoConfigureTestDatabase
到您的测试类中。我的测试通常是这样的:
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
public class MyRepositoryTest {
@Autowired
MyRepository repository;
@Test
public void test() throws Exception {
// Tests...
}
}
回答by jarosik
Simplest solution:
最简单的解决方案:
1) in src/main/resources have application.properties (production config):
1) 在 src/main/resources 中有 application.properties (production config):
spring.datasource.url=jdbc:mysql://localhost:3306/somedb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
and application-test.properties with HSQL config like:
和 application-test.properties 与 HSQL 配置,如:
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.database = HSQL
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect
spring.datasource.driverClassName = org.hsqldb.jdbcDriver
spring.datasource.url= jdbc:hsqldb:mem:scratchdb
spring.datasource.username = sa
spring.datasource.password =
2) Add HSQL dependency in pom.xml if you don't have it already.
2) 如果你还没有,在 pom.xml 中添加 HSQL 依赖项。
3) Annotate your test class with @ActiveProfiles("test").
3) 用@ActiveProfiles("test") 注释你的测试类。
Worked like charm in my case.
在我的情况下像魅力一样工作。
回答by Stephane Nicoll
@Sanjay has one way to put it but I find it confusing. You could just as well have only a production
profile that you enable when you're in production, something like:
@Sanjay 有一种表达方式,但我觉得它很混乱。您也可以只拥有一个production
在生产中启用的配置文件,例如:
spring.jpa.hibernate.ddl-auto: update
spring.datasource.url: jdbc:mysql://localhost:3306/dbname
spring.datasource.username: username
spring.datasource.password: password
And don't specify anything else. If you add an embedded database in test
scope, it will be available in your tests. If you run your tests with the default profile (no customization whatsoever), it won't find any database information (since these are stored in the production
profile). In that case, it will try to find an embedded database and start it for you. If you need more customization for some reason, you can have a application-test.properties
for those (you'll need to add ActiveProfiles("test")
to your test(s).
并且不要指定任何其他内容。如果您在test
范围内添加嵌入式数据库,它将在您的测试中可用。如果您使用默认配置文件(没有任何自定义)运行测试,它将找不到任何数据库信息(因为这些信息存储在production
配置文件中)。在这种情况下,它会尝试找到一个嵌入式数据库并为您启动它。如果您出于某种原因需要更多自定义,您可以application-test.properties
为这些自定义(您需要添加ActiveProfiles("test")
到您的测试中)。
回答by demaniak
Simple solution if building with maven
: just place an application.properties
file under src/test/resources
and edit as appropriate for testing.
简单的解决方案,如果使用maven
:只需放置一个application.properties
文件src/test/resources
并根据测试进行适当的编辑。
The Spring (Boot) Profile mechanism is a pretty powerful tool that, in scope, goes way beyond "swapping settings between test time and run time". Although, clearly, as demonstrated, it can do that also :)
Spring (Boot) Profile 机制是一个非常强大的工具,在范围内,它超越了“在测试时间和运行时间之间交换设置”。虽然,显然,正如所演示的,它也可以做到这一点:)
回答by 147.3k
With @SpringBootTest magic, you just need to do following two changes.
使用@SpringBootTest 魔法,您只需要进行以下两项更改即可。
- Add 'h2' test dependency in pom.xml
- 在 pom.xml 中添加“h2”测试依赖
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency>
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency>
@RunWith(SpringRunner.class) @SpringBootTest(classes = MySpringBootApplication.class) @AutoConfigureTestDatabase public class SpringBootTest{ @Autowired private RequestRepository requestRepository; }
@RunWith(SpringRunner.class) @SpringBootTest(classes = MySpringBootApplication.class) @AutoConfigureTestDatabase public class SpringBootTest{ @Autowired private RequestRepository requestRepository; }
Now all the spring jpa bean/repositories used in test will use h2 as backing database.
现在测试中使用的所有 spring jpa bean/存储库都将使用 h2 作为后备数据库。
2019-04-26 13:13:34.198 INFO 28627 --- [ main] beddedDataSourceBeanFactoryPostProcessor : Replacing 'dataSource' DataSource bean with embedded version
2019-04-26 13:13:34.199 INFO 28627 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'dataSource'
2019-04-26 13:13:36.194 INFO 28627 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:h2:mem:2784768e-f053-4bb3-ab88-edda34956893;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
2019-04-26 13:13:34.198 INFO 28627 --- [主要]beddedDataSourceBeanFactoryPostProcessor:用嵌入式版本替换'dataSource'DataSource bean
2019-04-26 13:13:34.199 INFO 28627 --- [main] osbfsDefaultListableBeanFactory:覆盖 bean 'dataSource' 的 bean 定义
2019-04-26 13:13:36.194 INFO 28627 --- [主要] osjdeEmbeddedDatabaseFactory :启动嵌入式数据库:url='jdbc:h2:mem:2784768e-f053-4bb3-ab88-edda34956891;DBY_CLOSE-ON假',用户名='sa'
Note: I still have 'spring-jpa' properties defined in 'application.properties' and I don't use any profiles. @AutoConfigureTestDatabasewill override existing jpa configurations with test defaults AutoConfigureTestDatabase.Replace.
注意:我仍然在“application.properties”中定义了“spring-jpa”属性,并且我没有使用任何配置文件。@ AutoConfigureTestDatabase将使用测试默认值 AutoConfigureTestDatabase.Replace 覆盖现有的 jpa 配置。
回答by RHronza
This solution enables common settings for develop and test. Is based on this solution: Override default Spring-Boot application.properties settings in Junit Test
此解决方案支持开发和测试的通用设置。基于此解决方案: Override default Spring-Boot application.properties settings in Junit Test
- application.propertiesin src/main/resources/application.properties
- application.properties中的src / main /资源/ application.properties
#common settings for DEVELOPMENT and TEST:
......
......
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:postgresql://localhost:5432/databasename
spring.datasource.username=postgres
spring.datasource.password=somepassword
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = none
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
- test.properties(src/main/resources/application.properties) which overrides and addsproperties in application.properties:
- test.properties(src/main/resources/application.properties)覆盖和添加application.properties 中的属性:
spring.datasource.url=jdbc:h2:mem:testdb;MODE=PostgreSQL
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=false
- settings in pom.xmlfor H2 and Postgre databases
- H2 和 Postgre 数据库的pom.xml 中的设置
<!-- h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- postgress -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
- In test class:
- 在测试类中:
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
public class ModelTest {
}