2016-11-18 43 views
1

我現在面臨的問題,讓每方法老虎鉗System.getProperty("name")值嘲諷System.class 實例後:模擬System.class在JUnit

@Test 
public void Test1()throws Exception { 
    PowerMockito.mockStatic(System.class); 
    // Configuration 
    when(System.getProperty("os.name")).thenReturn("Win"); 
} 
@Test 
public void Test2() throws Exception { 
    PowerMockito.mockStatic(System.class); 
    when(System.getProperty("os.name")).thenReturn("Linux"); 
} 

我們有兩個測試方法,當我們運行上面提到的兩個方法獨立,那麼我們得到正確的值System.getProperty("os.name")。但是當我們正在運行類(將在類中執行這兩種方法),那麼我們在第二種方法中獲得第一個方法的System.getProperty("os.name")值。 請建議。

提前致謝。

+1

你可以添加整個班級代碼嗎? – developer

+0

我無法複製,請提供整個測試類 –

+1

如果您想測試系統屬性,您應該將'System'套裝在橋中。想想像[系統規則](http://stefanbirkner.github.io/system-rules/)。 –

回答

0

如果你想改變系統屬性,爲什麼不只是System.setProperty("os.name", "")?這工作:

public class SystemPropertyTest { 

    @Test 
    public void testWin() { 
     System.setProperty("os.name", "Win"); 

     Assert.assertEquals("Win", System.getProperty("os.name")); 
    } 


    @Test 
    public void testLinux() { 
     System.setProperty("os.name", "Linux"); 

     Assert.assertEquals("Linux", System.getProperty("os.name")); 
    } 
} 
+0

修改系統屬性必須非常謹慎或避免,因爲它會影響你的env,因此它可能會影響其他測試。更糟糕的是,您需要在測試結束時重新設置舊值。 –

+0

正確,我將修改答案以包含系統屬性的恢復。但這基本上是PowerMock所做的,對吧?模擬靜態方法將產生全球影響。這是目的。 –

+0

關鍵是OP不需要靜態嘲弄來達到目標​​。 –

2

我會使用額外的外部庫,類似於System Rules

然後,您可以通過以下步驟實現你的目標:

public class SystemRulesTest { 

    @Rule 
    public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties(); 

    @Test 
    public void test1() { 
    System.setProperty("os.name", "Win"); 
    } 

    @Test 
    public void test2() { 
    System.setProperty("os.name", "Linux"); 
    } 
} 

注:系統規則,需要JUnit 4.9或以上的工作。