Skip to content

Commit

Permalink
More to TestWatcher from ExternalResource.
Browse files Browse the repository at this point in the history
  • Loading branch information
binkley committed Nov 22, 2014
1 parent 5cb72f7 commit fb4c976
Showing 1 changed file with 22 additions and 18 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package org.junit.contrib.java.lang.system.internal;

import org.apache.commons.io.output.TeeOutputStream;
import org.junit.contrib.java.lang.system.LogMode;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.io.output.TeeOutputStream;
import org.junit.contrib.java.lang.system.LogMode;
import org.junit.rules.ExternalResource;

public abstract class PrintStreamLog extends ExternalResource {
public abstract class PrintStreamLog extends TestWatcher {
private static final boolean NO_AUTO_FLUSH = false;
private static final String ENCODING = "UTF-8";
private final ByteArrayOutputStream log = new ByteArrayOutputStream();
Expand All @@ -23,14 +24,22 @@ protected PrintStreamLog(LogMode mode) {
}

@Override
protected void before() throws Throwable {
originalStream = getOriginalStream();
PrintStream wrappedStream = new PrintStream(getNewStream(), NO_AUTO_FLUSH,
ENCODING);
setStream(wrappedStream);
protected void starting(Description description) {
try {
originalStream = getOriginalStream();
PrintStream wrappedStream = new PrintStream(getNewStream(), NO_AUTO_FLUSH, ENCODING);
setStream(wrappedStream);
} catch (UnsupportedEncodingException e) {
throw new Error(e); // JRE missing UTF-8
}
}

private OutputStream getNewStream() throws UnsupportedEncodingException {
@Override
protected void finished(Description description) {
setStream(originalStream);
}

private OutputStream getNewStream() {
switch (mode) {
case LOG_AND_WRITE_TO_STREAM:
return new TeeOutputStream(originalStream, log);
Expand All @@ -42,11 +51,6 @@ private OutputStream getNewStream() throws UnsupportedEncodingException {
}
}

@Override
protected void after() {
setStream(originalStream);
}

protected abstract PrintStream getOriginalStream();

protected abstract void setStream(PrintStream wrappedLog);
Expand All @@ -60,7 +64,7 @@ public void clear() {

/**
* Returns the text written to the standard error stream.
*
*
* @return the text written to the standard error stream.
*/
public String getLog() {
Expand All @@ -70,4 +74,4 @@ public String getLog() {
throw new RuntimeException(e);
}
}
}
}

0 comments on commit fb4c976

Please sign in to comment.