Last active
July 11, 2019 01:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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