简体   繁体   English

Spring boot @Value 属性在测试用例中为空

[英]Spring boot @Value property is null in test cases

I want to get values from application.properties.我想从 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;

...

The thing is that appId and base are null in tests.问题是 appId 和 base 在测试中为空。 What is the reason for that?这是什么原因?

@Value is spring annotation and spring injects the value for properties into Spring-managed beans @Value是 spring 注释,spring 将属性值注入 Spring 管理的 bean

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.此注解可用于将值注入 Spring 管理的 bean 中的字段,并且可以在字段或构造函数/方法参数级别应用。

If you want this functionality working, you have to use @SpringBootTest annotation to load ApplicationContext, which is typically writing integration test如果你想让这个功能正常工作,你必须使用@SpringBootTest注解来加载ApplicationContext,这通常是编写集成测试

The @SpringBootTest annotation is useful when we need to bootstrap the entire container.当我们需要引导整个容器时,@SpringBootTest 注解很有用。 The annotation works by creating the ApplicationContext that will be utilized in our tests.注释通过创建将在我们的测试中使用的 ApplicationContext 来工作。

You can also inject value while writing unit test cases using ReflectionTestUtils , like example shown here您还可以在使用ReflectionTestUtils编写单元测试用例时注入价值,如此处所示示例

@Before
public void setUp() {
    ReflectionTestUtils.setField(springJunitService, "securityKey", "it's a security key");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM