[英]Why @Value are always null when run unit-test?
我編寫了Spring Boot
應用程序,並提出了一個條件調度服務的想法。 我決定通過@Value
填充application-test.yml
中的所有屬性並將其放入HashMap
中。
我不明白為什么在單元測試期間它總是null
,與它是否在HashMap
或@Value
填充屬性無關。
ReportService.java
:
@Component
public class ReportService {
@Value("${reports.name}")
private String name;
@Value("${reports.enabled}")
private Boolean enabled;
private final Map<String, Boolean> enabledReports = new HashMap<String, Boolean>() {{
put(name, enabled);
}};
boolean isEnabled(String reportName) {
System.out.println(enabledReports.keySet() + " : " + enabledReports.values());
System.out.println(name);
return false;
}
}
ReportServiceTest.java
:
@SpringBootTest
@SpringBootConfiguration
@RunWith(SpringRunner.class)
@TestPropertySource(locations="classpath:application-test.yml")
@EnableAutoConfiguration
public class ReportServiceTest {
private ReportService reportService = new ReportService();
@Test
public void test() {
reportService.isEnabled("reportName");
}
}
application-test.yml
:
reports:
name: "report"
enabled: false
我究竟做錯了什么?
reportService = new ReportService();
- 您正在自己創建 class 的實例,Spring 怎么知道需要注入一些東西?
只需讓 Spring 為您創建實例(例如,通過@Autowired
):
@Autowired
private ReportService reportService;
嘗試在變量初始化后構造 map 並使用 @Autowired 像https://stackoverflow.com/users/1121249/rkosegi提到:
@PostConstruct
public Map<String, Boolean> getEnabledReports(){
Map<String, Boolean> stringBooleanMap = new HashMap<>();
stringBooleanMap.put(name, enabled);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.