[英]Spring JUnit5 test not loading resource values
我知道有很多關於此的問題,但所有問題都建議使用@TestPropertySource
和@EnableConfigurationProperties
。 我已經使用過它們但仍然無法正常工作。
配置 class - src/main/java/com/demo/config/AppConfig.java
@Configuration
@ConfigurationProperties(prefix = "api")
@Getter
@Setter
public class AppConfig {
private List<String> providers;
private boolean enabled;
}
屬性源- src/test/resources/application-test.yml
api:
enabled: true
providers:
- prov1
- prov2
測試 class - src/test/../MyTest.java
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = MyTestConfiguration.class)
class MyTest {
@Autowired
private AppConfig appConfig;
@Test
void runTest() {//some code with breakpoint}
}
測試配置- src/test/.../MyTestConfiguration.java
@TestConfiguration
@TestPropertySource(locations = "classpath:application-test.yml")
@EnableConfigurationProperties(value = AppConfig.class)
@ActiveProfiles("test")
public class MyTestConfiguration {
}
當我運行測試runTest()
並檢查自動裝配的appConfig
值時, providers
為空且enabled
為false
。 這意味着未加載 yml 文件中的值。 我發現了類似的問題,但沒有答案。
我按照@sergey-tsypanov 的建議修改了MyTest
,然后刪除MyTestConfiguration
class。它有效並且appConfig
具有值。
@SpringBootTest(classes = AppConfig.class)
@EnableAutoConfiguration
@ActiveProfiles("test")
class MyTest {
@Autowired
private AppConfig appConfig;
@Test
void runTest() {//some code with breakpoint}
}
似乎即使我沒有@SpringBootApplication
,我也可以使用@SpringBootTest
和@EnableAutoConfiguration
。 我在 pom.xml 中有 spring 啟動依賴
我認為你需要更換
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = MyTestConfiguration.class)
和
@SpringBootTest(classes = {MyTestConfiguration.class})
然后application-test.yml
將被自動拾取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.