Skip to content

Instantly share code, notes, and snippets.

@kingargyle
Last active May 9, 2016 13:53
Show Gist options
  • Save kingargyle/8e75b8019e149dad3d3045cc1ca40e6f to your computer and use it in GitHub Desktop.
Save kingargyle/8e75b8019e149dad3d3045cc1ca40e6f to your computer and use it in GitHub Desktop.
A Junit 4 Rule to easily access the Log Output from Robolectric.
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.rules.ExternalResource;
import org.robolectric.shadows.ShadowLog;
public class RobolectricLoggingRule extends ExternalResource {
PrintStream loggingStream;
ByteArrayOutputStream loggingOutputStream;
PrintStream defaultStream;
@Override protected void before() throws Throwable {
super.before();
loggingOutputStream = new ByteArrayOutputStream();
loggingStream = new PrintStream(loggingOutputStream);
defaultStream = ShadowLog.stream;
ShadowLog.stream = loggingStream;
}
@Override public String toString() {
String result = "";
try {
result = loggingOutputStream.toString("UTF-8");
} catch (Exception ex) {
}
return result;
}
@Override protected void after() {
super.after();
ShadowLog.stream = defaultStream;
try {
loggingOutputStream.close();
} catch (Exception ex) {
// Do nothing.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment