如何模拟环境接口 [英] How to mock Environment Interface
问题描述
我必须使用 Environment 接口从属性文件中获取路径.在 Junits 中,我无法模拟环境接口.下面是我的代码.如果我要调用提到的方法,我想要一些随机的东西.我该怎么做?
I have to fetch path from the property file using Environment interface. In Junits I am not able to mock the Environment Interface. Below is my code. I want something random if I will call the method mentioned. How can I do it?
@Mock
private Class object;
@InjectMocks
Class2 object2;
Mockito.when(object.getFilePath()).thenReturn("Random String");
推荐答案
正如我在评论中所说,你不需要 Mockito,你可以使用 MockEnvironment
类来模拟 Environment代码> 来自 Spring.
您可以通过这种方式设置值:
As said in my comment, you don't need Mockito, you can use MockEnvironment
class to mock Environment
from Spring.
You can set values in this way :
MockEnvironment environment = new MockEnvironment();
environment.setProperty("yourKeyOne", "yourValue1");
environment.setProperty("yourKeyTwo", "yourValue2");
并且根据您的需要,您可以使用这个环境变量.例如,这里有一个 AnnotationConfigWebApplicationContext
实例:
And according to your need, you can use this environment variable.
For example, here is with an AnnotationConfigWebApplicationContext
instance :
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setEnvironment(environment);
这篇关于如何模拟环境接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!