[英]Why @Value are always null when run unit-test?
I write the Spring Boot
app and I come up with a conditional scheduling service idea.我编写了Spring Boot
应用程序,并提出了一个条件调度服务的想法。 I decided to populate all properties from application-test.yml
via @Value
and put it in the HashMap
.我决定通过@Value
填充application-test.yml
中的所有属性并将其放入HashMap
中。
What I don't understand why during unit-testing it always null
, independently of if it is in a HashMap
or @Value
populated property.我不明白为什么在单元测试期间它总是null
,与它是否在HashMap
或@Value
填充属性无关。
ReportService.java
: 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
: 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
: application-test.yml
:
reports:
name: "report"
enabled: false
What am I doing wrong?我究竟做错了什么?
reportService = new ReportService();
- you are creating instance of class yourself, how can Spring know that something needs to be injected? - 您正在自己创建 class 的实例,Spring 怎么知道需要注入一些东西?
Just let Spring to create instance for you (eg. via @Autowired
):只需让 Spring 为您创建实例(例如,通过@Autowired
):
@Autowired
private ReportService reportService;
Try to construct the map after the variables are initialized and also use @Autowired like https://stackoverflow.com/users/1121249/rkosegi mentioned:尝试在变量初始化后构造 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.