首页 > 编程语言 > 详细

在springboot测试中使用测试配置

时间:2020-06-15 12:38:11      阅读:76      评论:0      收藏:0      [点我收藏+]

在springboot测试中使用yml格式配置文件

在测试时我们需要单独的测试配置,springboot支持yml格式和古老的properties格式。

这里就使用yml格式的测试配置做简单说明。

可以使用两种注解方式使用测试配置:

使用@ActiveProfiles注解

使用方法:

在resoureces文件夹下新建application-test.yml文件,在里面填写测试的配置,例如

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: test
    url: jdbc:mysql://localhost:3307/test

在测试类中使用@ActiveProfiles("test")注解

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class IntegrationTest {

    @Value("${spring.datasource.url}")
    private String databaseUrl;
    @Value("${spring.datasource.username}")
    private String databaseUsername;
    @Value("${spring.datasource.password}")
    private String datasourcePassword;


    @Test
    public void setup() {
        System.out.println(databaseUrl);
    }
}   

这样就可以在测试时引入测试配置。

注意,这种方式是使用覆盖的方式加载配置,它会先加载application.yml中的默认配置,然后再加载application-test.yml中的测试配置,如果测试配置和默认不同,使用测试配置。如果未覆盖,则使用默认配置。

使用@TestPropertySource注解加载测试配置

@TestPropertySource(properties = {"spring.config.location=classpath:application-test.yml"})

这种方式只会加载测试目录resources下的application-test.yml文件,不能放到main/resources目录下。

使用实例如下:

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {"spring.config.location=classpath:application-test.yml"})

public class IntegrationTest {

    @Value("${spring.datasource.url}")
    private String databaseUrl;
    @Value("${spring.datasource.username}")
    private String databaseUsername;
    @Value("${spring.datasource.password}")
    private String datasourcePassword;


    @Test
    public void setup() {
        System.out.println(databaseUrl);
    }
}  

在springboot测试中使用测试配置

原文:https://www.cnblogs.com/acgq/p/13129822.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!