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

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

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

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

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)