Skip to content

Instantly share code, notes, and snippets.

@irof
Created November 13, 2011 01:21
Show Gist options
  • Save irof/1361438 to your computer and use it in GitHub Desktop.
Save irof/1361438 to your computer and use it in GitHub Desktop.
System.outをassertするためのRule
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
public class SystemOutRule implements MethodRule {
private ByteArrayOutputStream baos;
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
baos = new ByteArrayOutputStream();
PrintStream out = new PrintStream(baos);
System.setOut(out);
return base;
}
public String getString() {
return baos.toString();
}
}
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Rule;
import org.junit.Test;
import sample.SystemOutRule;
public class TestHelloWorld {
@Rule
public SystemOutRule rule = new SystemOutRule();
@Test
public void test() {
new HelloWorld().method();
assertThat(rule.getString(), is("Hello, world!"));
}
}
class HelloWorld {
public void method() {
System.out.print("Hello, world!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment