Mock System class to get system properties(模拟系统类以获取系统属性)
问题描述
我通过 Eclipse 中的 JVM 参数在系统变量中设置了一个文件夹路径,我试图在我的类中访问它:System.getProperty("my_files_path").
I have a folder path set in system variable through JVM arguments in Eclipse and I am trying to access it in my class as:
System.getProperty("my_files_path").
在为此类编写 junit 测试方法时,我尝试模拟此调用,因为测试类不考虑 JVM 参数.我使用 PowerMockito 模拟静态 System 类,并尝试在调用 System.getProperpty 时返回一些路径.
While writing junit test method for this class, I tried mocking this call as test classes do not consider JVM arguments. I have used PowerMockito to mock static System class and tried returning some path when System.getProperpty is being called.
在类级别有 @RunWith(PowerMockRunner.class) 和 @PrepareForTest(System.class) 注释.但是, System 类没有被嘲笑,因此我总是得到空结果.任何帮助表示赞赏.
Had @RunWith(PowerMockRunner.class) and @PrepareForTest(System.class) annotations at class level. However, System class is not getting mocked as a result I always get null result.
Any help is appreciated.
推荐答案
感谢 Satish.除了稍作修改外,此方法有效.我写了 PrepareForTest(PathFinder.class),为测试用例而不是 System.class 准备我正在测试的类
Thanks Satish. This works except with a small modification. I wrote PrepareForTest(PathFinder.class), preparing the class I am testing for test cases instead of System.class
另外,由于模拟只工作一次,我在模拟后立即调用了我的方法.我的代码仅供参考:
Also, as mock works only once, I called my method right after mocking. My code just for reference:
@RunWith(PowerMockRunner.class)
@PrepareForTest(PathInformation.class)
public class PathInformationTest {
private PathFinder pathFinder = new PathFinder();
@Test
public void testValidHTMLFilePath() {
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getProperty("my_files_path")).thenReturn("abc");
assertEquals("abc",pathFinder.getHtmlFolderPath());
}
}
这篇关于模拟系统类以获取系统属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:模拟系统类以获取系统属性
基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
