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

标签 java mocking environment-variables system powermock

我在 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/

相关文章:

java - 为什么 2010 年 12 月 31 日返回 1 作为一年中的一周?

mocking - stub 中的 any_number_of_times 方法的替代方法

java - Camel : Ignore some messages in mock endpoint

java - 在没有 ApplicationContext 文件的情况下测试 Spring Controller 服务

powershell - Powershell和cmd环境变量

amazon-web-services - 如何在AWS Lambda上使用环境变量?

java - 如何为 JTree/JList/JTable 设置助记符

java - 如何基于设备切换加速度计 Axis ?

vbscript - 在经典 ASP 中获取环境变量

java - Java 中的序列化对象