2016-11-03 2 views
0

사용자가 ESC을 입력 할 때 콘솔 앱의 TestNgtest 케이스를 쓰려고합니다. 어느 시점에서 응용 프로그램은 메시지를 인쇄 한 다음 종료해야합니다. 메시지가 인쇄되면 TestNg에서 테스트하도록합니다.출구가있는 TestNg 콘솔 앱

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을 코드입니다 :

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와 응용 프로그램이 종료 나는 심지어 assertTrue 라인에 도착하지 않는 때문에, TestNG를 그냥 전에 종료 다음은 응용 프로그램 코드입니다. 이것을 시험 할 올바른 방법이 있습니까?

+0

esc를 눌러 다른 클래스 (가능하면'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으로 재설정 할 수 있습니다.