2012-07-16 90 views
1

我在JUnit寫一個測試案例的Class傳遞給Runtime.getRuntime.exit(值)值,可以把它叫做C1其內部調用Runtime.getRuntime.exit(somevalue)如何獲得了在JUnit測試案例

C1有一個main方法,它接受一些arguments並根據通過arguments做具體的任務創建一個CommandLine然後。現在

執行調用Runtime.getRuntime.exit(somevalue)後的所有任務。 somevalue定義任務是否成功執行(意味着somevalue爲0)或有錯誤(意味着某個值爲1)。

在這個JUnit測試案例中,我必須得到這個somevalue並檢查它是否是所需的somevalue或不。

我如何在JUnit測試案例的somevalue

+0

您使用的是模擬框架? – 2012-07-16 13:25:49

+0

簡單的JUnit測試用例類。 – JHS 2012-07-16 13:28:48

回答

3

您可以覆蓋安全管理器捕捉到退出代碼,如果你使用一個模擬框架會比較簡潔:

@Test 
public void when_main_is_called_exit_code_should_be_1() throws Exception { 
    final int[] exitCode = new int[1]; 
    System.setSecurityManager(new SecurityManager() { 
     @Override 
     public void checkExit(int status) { 
      exitCode[0] = status; 
      throw new RuntimeException(); 
     }}); 

    try { main(); } catch(Exception e) {} 

    assertEquals(exitCode[0], 1); 
} 

public static void main() { 
    System.exit(1); 
}