模拟系统类以获取系统属性

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());
    }
}

这篇关于模拟系统类以获取系统属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)