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