我通过 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());
}
}
这篇关于模拟系统类以获取系统属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!