Skip to content

Instantly share code, notes, and snippets.

@ClassCubeGists
Last active July 11, 2019 01:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ClassCubeGists/b5ae82751a0b6f4baa4b05b1deec97dd to your computer and use it in GitHub Desktop.
Save ClassCubeGists/b5ae82751a0b6f4baa4b05b1deec97dd 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