Mock System类获取系统属性 [英] Mock System class to get system properties
问题描述
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屋!