gpt4 book ai didi

java - Spring Boot 2.1 : Not loading property from application-test. yml

转载 作者:行者123 更新时间:2023-12-01 14:14:24 25 4
gpt4 key购买 nike

我试图在我的单元测试执行期间从 application-test.yml 读取一个属性,但相反,正在读取 application-dev.yml 中的属性。我没有 application.yml 文件。感谢帮助。

AppProperties.java

@Component
@ConfigurationProperties(prefix="app")
public class AppProperties {

private String test;

public String getTest() {
return this.test;
}

public void setTest(String test) {
this.test = test;
}
}

应用程序-dev.yml
spring:
profiles: dev
application:
name: testApplication
app:
test: 1

应用程序-test.yml
spring:
profiles: test
application:
name: testApplication
app:
test: 2

AppServiceTest.java
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AppProperties.class}, initializers= ConfigFileApplicationContextInitializer.class)
@EnableConfigurationProperties
@ActiveProfiles("test")
public class AppServiceTest{

@Autowired
AppProperties appProperties;

@Test
public void test(){
appProperties.getTest();
//This returns "1" instead of the desired "2"
}

最佳答案

使用 @SpringBootTest单元测试类的注解

Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication. In addition to @SpringBootTest a number of other annotations are also provided for testing more specific slices of an application.


@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AppProperties.class}, initializers=
ConfigFileApplicationContextInitializer.class)
@EnableConfigurationProperties
@SpringBootTest
@ActiveProfiles("test")
public class AppServiceTest{

@Autowired
AppProperties appProperties;

@Test
public void test(){
appProperties.getTest();
//This returns "1" instead of the desired "2"
}

关于java - Spring Boot 2.1 : Not loading property from application-test. yml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54084217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com