繁体   English   中英

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 管理的 bean

此注解可用于将值注入 Spring 管理的 bean 中的字段,并且可以在字段或构造函数/方法参数级别应用。

如果你想让这个功能正常工作,你必须使用@SpringBootTest注解来加载ApplicationContext,这通常是编写集成测试

当我们需要引导整个容器时,@SpringBootTest 注解很有用。 注释通过创建将在我们的测试中使用的 ApplicationContext 来工作。

您还可以在使用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