Skip to content

Instantly share code, notes, and snippets.

@iqbmo04
Forked from ClassCubeGists/OutputCaptureTest.java
Created June 14, 2019 13:07
Show Gist options
  • Select an option

  • Save iqbmo04/9b8b20dc1a1ac28d474bafb21f00812f to your computer and use it in GitHub Desktop.

Select an option

Save iqbmo04/9b8b20dc1a1ac28d474bafb21f00812f to your computer and use it in GitHub Desktop.
Capturing stdOut and stdErr as part of a JUnit test. See https://classcube.com/junit-compare-output/ for explanations.
import java.util.*;
import java.io.*;
import static org.junit.Assert.*;
import org.junit.Test;
@SuppressWarnings( "unchecked" )
public class OutputCaptureTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
@Test( timeout = 250 )
public void test() throws Exception {
captureOut();
// Run whatever code you're testing
String theOutput = getOut();
// Compare what you expect with theOutput
}
/**
* Turns on stdOut output capture
*/
private void captureOut() {
System.setOut( new PrintStream( outContent ) );
}
/**
* Turns on stdErr output capture
*/
private void captureErr() {
System.setErr( new PrintStream( errContent ) );
}
/**
* Turns off stdOut capture and returns the contents
* that have been captured
*
* @return
*/
private String getOut() {
System.setOut( new PrintStream( new FileOutputStream( FileDescriptor.out ) ) );
return outContent.toString().replaceAll( "\r", "" );
}
/**
* Turns off stdErr capture and returns the contents
* that have been captured
*
* @return
*/
private String getErr() {
System.setErr( new PrintStream( new FileOutputStream( FileDescriptor.out ) ) );
return errContent.toString().replaceAll( "\r", "" );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment