2016-11-03 10 views
0

ユーザーがESCを入力したときにコンソールアプリケーションのTestNgtestケースを書き込もうとしています。この時点で、アプリケーションはメッセージを出力して終了する必要があります。 TestNgは、メッセージが印刷されるかどうかをテストします。ここでは、アプリケーション・コードがあります:TestNgコンソールアプリケーションExit with

public class ApplicationTest { 
    private Application app; 
    private ByteArrayInputStream in; 
    private ByteArrayOutputStream out; 

    @BeforeMethod 
    public void setUp() throws Exception { 
     app = new Application(); 
     out = new ByteArrayOutputStream(); 
     System.setOut(new PrintStream(out)); 
    } 

    @AfterMethod 
    public void tearDown() throws Exception { 
     System.setIn(System.in); 
    } 

    @Test 
    public void testESCInput() throws Exception { 
     in = new ByteArrayInputStream("ESC".getBytes()); 
     System.setIn(in); 
     app.processInput(new Scanner(System.in)); 
     assertTrue(out.toString().contains("Bye")); 
    } 
} 

しかしSystem.exitとアプリケーションが終了するので、私もTestNGのは、ちょうどその前に終了しassertTrueラインに得ることはありません:

public class Application { 
    public static void doSomething(Scanner scanner) { 
    String inputString = scanner.nextLine(); 

    if("ESC".equals(inputString.toUpperCase())) { 
     System.out.println("Bye"); 
     System.exit(0); 
    } 
    } 
} 

ここでJUnitのコードです。これをテストする正しい方法はありますか?

+0

エスケープが別のクラス(おそらく 'Runnable')に押されたときの動作を外部化することができます。次に、テストのための模擬実装を提供することができます。 –

答えて

0

SecurityManagerを使用すると、終了試行を拒否してから、予期しない例外を回避してテストを構築することができます。これはJUnitのと連動し、簡単にこれは、任意の終了の試みに満足している簡単なテスト、であるTestNGの

public class ExitTest { 
    public static class RejectedExitAttempt extends SecurityException { 
    private int exitStatus; 
    public RejectedExitAttempt(int status) { 
     exitStatus=status; 
    } 
    public int getExitStatus() { 
     return exitStatus; 
    } 
    @Override 
    public String getMessage() { 
     return "attempted to exit with status "+exitStatus; 
    } 
    } 

    @Before 
    public void setUp() throws Exception { 
    System.setSecurityManager(new SecurityManager() { 
     @Override 
     public void checkPermission(Permission perm) { 
      if(perm instanceof RuntimePermission && perm.getName().startsWith("exitVM.")) 
       throw new RejectedExitAttempt(
        Integer.parseInt(perm.getName().substring("exitVM.".length()))); 
     } 
    }); 
    } 

    @After 
    public void tearDown() throws Exception { 
    System.setSecurityManager(null); 
    } 

    @Test(expected=RejectedExitAttempt.class) 
    public void test() { 
    System.exit(0); 
    } 
} 

に適合させる必要があります。特定の終了ステータスが必要な場合は、例外をキャッチしてステータスを確認する必要があります。

このカスタムSecurityManagerは他のアクションを許可するので、セキュリティマネージャをnullにリセットすることができます。

関連する問題