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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM