![](/img/trans.png)
[英]Using property from @TestPropertySource properties results in NullPointerException
[英]Properties are always null @ ConfigurationProperties when using @ TestPropertySource
使用@TestPropertySource
時,屬性始終為 null @ConfigurationProperties
配置文件application.yml :
integration:
some:
configuration:
userInfo: testUser
配置 class
@Component
@Data
@ConfigurationProperties(prefix="integration.some.configuration")
public class SomeProperties {
private String userInfo;
}
服務 class:
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(SomeProperties.class)
public class SomeServiceImpl {
private final SomeProperties someProperties;
public String get() {
return someProperties.getUserInfo();
}
}
測試夾具:
@SpringJUnitConfig({
SomeServiceImpl.class,
SomeProperties.class})
@TestPropertySource(properties = {
"integration.some.configuration.userInfo=someUser"
})
class SomeServiceImplTest {
@Autowired
SomeServiceImpl someServiceImpl;
@Test
void someTest() {
String user = someServiceImpl.get();
....
}
}
在上面的測試中,注入的用戶總是null
。
你錯過了自動裝配
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(SomeProperties.class)
public class SomeServiceImpl {
@Autowired // <--------
private final SomeProperties someProperties;
public String get() {
return someProperties.getUserInfo();
}
}
此外,由於您將@Component
放置在 SomeProperties 上,您可以刪除@EnableConfigurationProperties(SomeProperties.class)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.