2010-01-30 4 views
24

JUnit을 사용하여 콘솔 기반 애플리케이션의 테스트를 자동화하는 통합 테스트를 작성하고 있습니다. 신청서는 숙제이지만이 부분은 숙제가 아닙니다. 이 테스트를 자동화하여 생산성을 높이고 싶습니다. 이전 테스트 단계로 돌아가서 다시 테스트 할 필요가 없습니다. (단위 테스트를 사용하는 표준적인 이유)Java, Junit - 유닛 테스트에 사용할 표준 입력/출력 캡쳐

어쨌든 출력 캡처에 관한 기사를 찾을 수 없으므로 assertEquals을 수행하거나 자동 입력을 제공 할 수 없습니다. 출력/입력이 콘솔/출력 창으로 이동하는지 상관하지 않습니다. 테스트를 실행하고 출력이 입력에 따라 예상되는 것만 확인하면됩니다.

누구나 도움이되는 기사 또는 코드가 있습니다.

+0

@dfa, 나는 동의하지 않는다. 실제로는 비슷하지만 충분히 다릅니다. –

+0

... 대답은 동일합니다 ... –

+1

다른 스레드가 이제 더 나은 대답을 가지고 있습니다. jUnit StandardOutputStreamLog 시스템 규칙을 사용합니다. stderr 및 stdin에 대한 시스템 규칙도 있습니다. –

답변

38

System.setOut() (및 System.setErr())을 사용하면 출력을 임의의 인쇄 스트림으로 리디렉션 할 수 있습니다. 프로그래밍 방식으로 읽을 수있는 출력이 될 수 있습니다. 예를 들어

:

final ByteArrayOutputStream myOut = new ByteArrayOutputStream(); 
System.setOut(new PrintStream(myOut)); 

// test stuff here... 

final String standardOutput = myOut.toString(); 
+1

간단히'PrintStream _out = System.out;'가 실행되지 않습니까? –

+0

기존의 출력 스트림에 대한 참조가 있지만, 일반적인'PrintStream' 인터페이스에서 적절한 방법이 없기 때문에 * 아무것도 읽을 수 없습니다. 이 기술은 출력 방법을 알고있는 특정 인쇄 스트림으로 출력을 설정하는 것과 관련이 있습니다. –

7

System 클래스 방법을 setIn(), setOut() 및 표준 입력, 출력 및 오류 스트림을 설정할 수 setErr(), 예를 가지고 에 따라 검사 할 수있는 ByteArrayOutputStream으로 변경하십시오.

1

다음은 ByteArrayOutputStream 대신 솔루션입니다. System.setOut의 아이디어에 아무 것도 추가하지 않습니다. 오히려 모든 것을 캡처하는 것보다 나은 구현을 ByteArrayOutputStream에 공유하려고합니다. 나는 선택된 정보만을 포착하고 모든 로그 메시지를 나중에 처리하기 위해 balckbox (크기가?)에 모두 캡처하는 대신 기록 될 때 콘솔에 나타나도록하는 것을 선호합니다. 여기

/** 
* Once started, std output is redirected to this thread. 
* Thread redirects all data to the former system.out and 
* captures some strings.*/ 
static abstract class OutputCaputre extends Thread { 

    // overrdie these methods for System.err 
    PrintStream getDownstream() { return System.out;} 
    void restoreDownstream() { System.setOut(downstream);} 

    // will be called for every line in the log 
    protected abstract void userFilter(String line); 

    final PrintStream downstream; 
    public final PipedInputStream pis; 
    private final PipedOutputStream pos; 
    OutputCaputre() throws IOException { 
     downstream = getDownstream(); 

     pos = new PipedOutputStream(); 
     pis = new PipedInputStream(pos); 
     System.setOut(new PrintStream(pos)); 

     start(); 
    } 

    public void run() { 
     try { 
      BufferedReader br = new BufferedReader(new InputStreamReader(pis)); 

      // once output is resotred, we must terminate 
      while (true) { 
       String line = br.readLine(); 
       if (line == null) { 
        return; 
       } 
       downstream.println(line); 
       userFilter(line); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void terminate() throws InterruptedException, IOException { 
     restoreDownstream(); // switch back to std 
     pos.close(); // there will be no more data - signal that 
     join(); // and wait until capture completes 
    } 
}; 

클래스를 사용하는 예입니다

OutputCaputre outputCapture = new OutputCaputre() { 
    protected void userFilter(String line) { 
     downstream.println("Capture: " + line); 
    }  
}; 
System.out.println("do you see me captured?"); 
// here is your test  
outputCapture.terminate(); // finally, stop capturing 
관련 문제