2012-07-16 25 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); 
}