[英]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.