問題描述
我通過 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());
}
}
這篇關于模擬系統類以獲取系統屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!