在springboot测试中使用测试配置

在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);
    }
}  

posted on 2020-06-15 11:22  acgq  阅读(8666)  评论(0编辑  收藏  举报

导航