我在 Eclipse 中通过 JVM 参数在系统变量中设置了一个文件夹路径,我试图在我的类中访问它:
System.getProperty("my_files_path")
。
在为此类编写 junit 测试方法时,我尝试模拟此调用,因为测试类不考虑 JVM 参数。我使用 PowerMockito 来模拟静态系统类,并尝试在调用 System.getProperpty
时返回一些路径。
在类级别有 @RunWith(PowerMockRunner.class)
和 @PrepareForTest(System.class)
注释。但是,系统类没有被 mock ,因为我总是得到空结果。
任何帮助表示赞赏。
最佳答案
谢谢萨蒂什。除了一个小的修改外,这是有效的。我写了 PrepareForTest(PathFinder.class),为测试用例准备我正在测试的类而不是 System.class
另外,由于 mock 只工作一次,所以我在 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());
}
}
关于java - 模拟系统类以获取系统属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20404276/