Spring boot @Value 属性 在测试用例中为空
Spring boot @Value property is null in test cases
我想从 application.properties 中获取值。
@ExtendWith(MockitoExtension.class)
public class CurrencyServiceTest {
@Mock
private OpenExchangeRatesClient openExchangeRatesClient;
@Value("${openexchangerates.app.id}")
private String appId;
@Value("${openexchangerates.currency.base}")
private String base;
...
问题是 appId 和 base 在测试中为空。这是什么原因?
@Value 是 spring 注释,spring 将属性值注入 Spring-managed beans
This annotation can be used for injecting values into fields in Spring-managed beans, and it can be applied at the field or constructor/method parameter level.
如果你想让这个功能正常工作,你必须使用@SpringBootTest注解来加载ApplicationContext,这通常是编写集成测试
The @SpringBootTest annotation is useful when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.
您还可以在使用 ReflectionTestUtils
编写单元测试用例时注入值,如所示示例 here
@Before
public void setUp() {
ReflectionTestUtils.setField(springJunitService, "securityKey", "it's a security key");
}
我想从 application.properties 中获取值。
@ExtendWith(MockitoExtension.class)
public class CurrencyServiceTest {
@Mock
private OpenExchangeRatesClient openExchangeRatesClient;
@Value("${openexchangerates.app.id}")
private String appId;
@Value("${openexchangerates.currency.base}")
private String base;
...
问题是 appId 和 base 在测试中为空。这是什么原因?
@Value 是 spring 注释,spring 将属性值注入 Spring-managed beans
This annotation can be used for injecting values into fields in Spring-managed beans, and it can be applied at the field or constructor/method parameter level.
如果你想让这个功能正常工作,你必须使用@SpringBootTest注解来加载ApplicationContext,这通常是编写集成测试
The @SpringBootTest annotation is useful when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.
您还可以在使用 ReflectionTestUtils
编写单元测试用例时注入值,如所示示例 here
@Before
public void setUp() {
ReflectionTestUtils.setField(springJunitService, "securityKey", "it's a security key");
}