Mock System类获取系统属性 [英] Mock System class to get system properties

查看:1544
本文介绍了Mock System类获取系统属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过Eclipse中的JVM参数在系统变量中设置的文件夹路径,我试图在我的类中访问它:
System.getProperty(my_files_path)



在为该类编写junit测试方法时,我尝试嘲笑此调用,因为测试类不考虑JVM参数。我使用PowerMockito来模拟静态系统类,并尝试在 System.getProperpty 被调用时返回一些路径。



在类级别有 @RunWith(PowerMockRunner.class) @PrepareForTest(System.class)注释。但是,系统类没有被嘲笑,所以我总是得到空的结果。
任何帮助不胜感激。

解决方案

谢谢Satish。除了进行小的修改之外,它的工作。我写了PrepareForTest(PathFinder.class),准备我正在测试测试用例而不是System.class的类



另外,由于mock只有一次,我打电话给我的方法嘲笑之后。
我的代码仅供参考:

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


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").

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.

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.

解决方案

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆