sai*_*nki 10 java system mocking environment-variables powermock
我不得不通过在Eclipse的JVM参数系统变量设定的文件夹路径,我试图访问它在我的课为:
System.getProperty("my_files_path").
在为这个类编写junit测试方法时,我尝试模拟这个调用,因为测试类不考虑JVM参数.我已经使用PowerMockito来模拟静态System类,并尝试System.getProperpty在调用时返回一些路径.
在课堂上有注释@RunWith(PowerMockRunner.class)和@PrepareForTest(System.class)注释.但是,System类没有被模拟,因此我总是得到null结果.任何帮助表示赞赏.
sai*_*nki 14
谢谢Satish.除了小修改外,这个工作正常.我编写了PrepareForTest(PathFinder.class),准备我正在测试测试用例而不是System.class的类
此外,由于模拟只工作一次,我在模拟后立即调用了我的方法.我的代码仅供参考:
@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());
}
}
Run Code Online (Sandbox Code Playgroud)
有些类PowerMock无法以通常的方式进行模拟.看这里:
但是,这可能仍然无效.按照"良好设计"的偏好,你可以回到这些:
重构你的代码!使用System属性传递文件路径可能不是最好的方法.为什么不使用加载到Properties对象中的属性文件?为什么不为需要知道此路径的组件使用getter/setter?有很多更好的方法可以做到这一点.
我想到不这样做的唯一原因是你试图围绕你"无法"修改的代码包装测试工具.
使用@Before和@After方法将System属性设置为测试的某个已知值.你甚至可以把它作为@Test方法本身的一部分.这比试图模拟PowerMock更容易.打电话吧System.setProperty("my_files_path","fake_path");
在测试中设置系统属性,并确保在测试后使用库系统规则的规则RestoreSystemProperties将其还原.
public class PathInformationTest {
private PathFinder pathFinder = new PathFinder();
@Rule
public TestRule restoreSystemProperties = new RestoreSystemProperties();
@Test
public void testValidHTMLFilePath() {
System.setProperty("my_files_path", "abc");
assertEquals("abc",pathFinder.getHtmlFolderPath());
}
}
Run Code Online (Sandbox Code Playgroud)
系统类被声明为最终类,不能被 PowerMock之类的库嘲笑。这里发布的几个答案不正确。如果使用的是Apache System Utils,则可以使用getEnvironmentVariablemethod而不是直接调用System.getenv。由于未将SystemUtils声明为final,因此可以对其进行模拟。
| 归档时间: |
|
| 查看次数: |
30808 次 |
| 最近记录: |