2014-12-15 7 views
1

이 내 주요 방법이 JUnit 테스트를 실행junit 테스트에서`main()`이`timer '에 던져진 예외를 잡아 내지 않는 이유는 무엇입니까?

public static void main(String... args) throws ClassNotFoundException { 
    String[] classAndMethod = args[0].split("#"); 
    if (helpCmd(args)) { 
     printHelpForTest(classAndMethod[1]); 
     System.exit(0); 
    } 

    Result result = runTest(classAndMethod); 
    exitIfTimeOutExceptionThrown(result); 
    System.exit(result.wasSuccessful() ? 0 : 1); 
} 

private static void exitIfTimeOutExceptionThrown(Result result) { 
    boolean isTimeOut = Iterables.filter(result.getFailures(), CodeBlockTimeOutException.class).iterator().hasNext(); 
    if (isTimeOut) 
    { 
     System.exit(2); 
    } 
} 

:

@Test 
    public void sendSearchRequest() throws Exception { 

... 

     setTimeOut(); 

... 
    } 

private void setTimeOut() { 
    if (criticalBlockTimeOut != null) { 
     TimerTask timerTask = new TimerTask() { 
      @Override 
      public void run() { 
       throw new CodeBlockTimeOutException(); 
       //thread.interrupt(); 

      } 
     }; 
     new Timer().schedule(timerTask, Long.parseLong(criticalBlockTimeOut)); 
    } 
} 

난 내 코드가 CodeBlockTimeOutException 던져 볼 이유하지만 메인 결코 코드 2 종료?

어떻게하면 기본 스레드에서 잡힐 수 있습니까?

+0

가능한 중복 (http://stackoverflow.com/questions/11448214/unable-to-catch-exception-from- [TimerTask를 스레드에서 예외를 잡을 수 없습니다] timertask-thread) – Petesh

답변

6

다른 스레드에서 타이머 이벤트가 발생합니다. 주 스레드는 오류없이 종료합니다. 다른 곳에서 오류가 기록됩니다. 예외가 발생하면 예약 된 작업에서 휘발성 플래그를 설정해야합니다. 주 스레드에서 작업이 완료 될 때까지 기다린 다음이 플래그를 확인하십시오.

여기 보라 : Waiting for a Timer to finish in Java 또는 Java: Wait for TimerTask to complete before continuing execution

+0

어떻게 주 스레드에서 잡힐 수 있습니까? –

+0

하지만 메인 스레드를 바로 끝내고 싶습니다. –

+0

JUnit이 메인 스레드에서 실행되고 있지 않습니다. 다른 스레드는 테스트 환경에 대해 아무 것도 모른다. – Mikhail