Фед*_*аев 5 java testing mockito spring-boot
我想从 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;
...
Run Code Online (Sandbox Code Playgroud)
问题是 appId 和 base 在测试中为 null。这是什么原因呢?
@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");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5174 次 |
| 最近记录: |