問題描述
我通過 Eclipse 中的 JVM 參數(shù)在系統(tǒng)變量中設(shè)置了一個(gè)文件夾路徑,我試圖在我的類中訪問它: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 測(cè)試方法時(shí),我嘗試模擬此調(diào)用,因?yàn)闇y(cè)試類不考慮 JVM 參數(shù).我使用 PowerMockito 模擬靜態(tài) System 類,并嘗試在調(diào)用 System.getProperpty
時(shí)返回一些路徑.
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.
在類級(jí)別有 @RunWith(PowerMockRunner.class)
和 @PrepareForTest(System.class)
注釋.但是, System 類沒有被嘲笑,因此我總是得到空結(jié)果.任何幫助表示贊賞.
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),為測(cè)試用例而不是 System.class 準(zhǔn)備我正在測(cè)試的類
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
另外,由于模擬只工作一次,我在模擬后立即調(diào)用了我的方法.我的代碼僅供參考:
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());
}
}
這篇關(guān)于模擬系統(tǒng)類以獲取系統(tǒng)屬性的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!