在Spring中为测试目的配置特定的内存数据库

wqsoz72f  于 2023-04-04  发布在  Spring
关注(0)|答案(8)|浏览(101)

如何配置我的 *Sping Boot * 应用程序,以便当我运行 * 单元测试 * 时,它将使用内存中数据库,如H2/HSQL,但当我运行 Spring Boot 应用程序时,它将使用生产数据库PostgreSQL/MySQL

qqrboqgw

qqrboqgw1#

Spring配置文件可以用于此。这将是一种特定的方式:
具有特定于环境的属性文件:

应用.属性

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中有 MySQLH2 驱动,如下所示:

<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")注解Test类。

rqmkfv5c

rqmkfv5c2#

另一种方法是将注解@AutoConfigureTestDatabase添加到测试类中。我的测试通常看起来像这样:

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
public class MyRepositoryTest {

    @Autowired
    MyRepository repository;

    @Test
    public void test() throws Exception {
        // Tests...
    }
}

请注意,嵌入式数据库依赖项需要添加到pom.xml文件中。对于嵌入式数据库,此注解不是必需的,即使仅在pom文件中添加依赖项也可以工作。

mrfwxfqh

mrfwxfqh3#

使用@SpringBootTest魔法,您只需要做以下两个更改。
1.在pom.xml中添加“h2”测试依赖项

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

1.使用@AutoConfigureTestDatabase

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
@AutoConfigureTestDatabase
public class SpringBootTest{

    @Autowired
    private RequestRepository requestRepository;
}

现在测试中使用的所有spring jpa bean/repositories都将使用h2作为后台数据库。
2019-04-26 13:13:34.198 INFO 28627 --- [ main] beddedDataSourceBeanFactoryPostProcessor:使用嵌入版本替换“dataSource”DataSource bean
2019-04-26 13:13:34.199 INFO 28627 --- [ main] o.s.b.f.s.DefaultListableBeanFactory:正在重写bean“dataSource”的bean定义
2019-04-26 13:13:36.194 INFO 28627 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory:正在启动嵌入式数据库:网址:http://www.jdbc.h2.cn数据库关闭延迟=-1;DB_CLOSE_ON_EXIT= false ',username='sa'
注意:我仍然在'application.properties'中定义了'spring-jpa'属性,并且我没有使用任何配置文件。@AutoConfigureTestDatabase将使用测试默认值AutoConfigureTestDatabase. Replace覆盖现有的jpa配置。

hmtdttj4

hmtdttj44#

最简单的解决方案:
1)在src/main/resources中有application.properties(产品配置):

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

和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)如果您还没有HSQL依赖项,请在pom.xml中添加它。
3)使用@ActiveProfiles(“test”)注解测试类。
对我来说就像魅力一样。

disho6za

disho6za5#

@Sanjay有一种说法,但我觉得它令人困惑。你也可以只在生产环境中启用production配置文件,比如:

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

如果在test范围内添加嵌入式数据库,它将在测试中可用。(没有任何定制),它不会找到任何数据库信息(因为这些存储在production配置文件中)。在这种情况下,它会尝试找到一个嵌入式数据库并为你启动它。如果你出于某种原因需要更多的定制,你可以有一个application-test.properties(你需要将ActiveProfiles("test")添加到你的测试中)。

3qpi33ja

3qpi33ja6#

使用maven构建的简单解决方案:只需在src/test/resources下放置一个application.properties文件,并根据需要进行编辑以进行测试。
Spring( Boot )Profile机制是一个非常强大的工具,在范围内,远远超出了“在测试时和运行时之间交换设置”。尽管如此,很明显,正如所展示的那样,它也可以做到这一点:)

zvms9eto

zvms9eto7#

此解决方案启用开发和测试的公共设置。基于此解决方案:Override default Spring-Boot application.properties settings in Junit Test
1.application.properties在src/main/resources/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

1.test.properties(src/main/resources/application.properties),覆盖并添加www.example.com中的属性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
  1. H2和Postgre数据库的pom.xml中的设置
<!-- h2 -->
      <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
      </dependency>

    <!-- postgress -->
      <dependency>
         <groupId>org.postgresql</groupId>
         <artifactId>postgresql</artifactId>
      </dependency>

1.测试类中:

@RunWith(SpringRunner.class)
    @SpringBootTest
    @TestPropertySource(locations = "classpath:test.properties")
    public class ModelTest { 

    }
nhaq1z21

nhaq1z218#

我有一个多模块的Gradle SpringBoot应用程序,其中包含以下模块
1.employeemanagerApp-其中我的SpringApplication主类
1.employeemanagerIntTests-我的 cucumber 测试
我的要求是在应用程序启动时使用MySQL DB,在Cucumber集成测试期间使用H2

**解决方案:**在employeemanagerApp模块src/main/resources中,我放置了application.properties,内容如下

#My SQL Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/employeemanager
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update  spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

在集成测试模块(employeemanagerIntTests)src/test/resources中,我将application.properties与以下内容放在一起

#H2 In-Memory DB Configuration
spring.datasource.url=jdbc:h2://mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.format_sql=true

在我的步骤定义类中,我只添加了这些注解

@CucumberContextConfiguration
@SpringBootTest(classes = SpringBootApplicationMainClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

在build.gradle文件中,我添加了H2依赖项

testImplementation 'com.h2database:h2:1.4.200'

因此,当我运行我的测试时,H2是活动的,所有的创建、更新、读取和删除测试都是成功的

相关问题