Created
November 13, 2011 01:21
-
-
Save irof/1361438 to your computer and use it in GitHub Desktop.
System.outをassertするためのRule
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.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(); | |
} | |
} |
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 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