业务类:
public class OutDemo {
public void print(String content) {
System.out.print(content);
}
}
测试类:
public class OutDemoTest {
private StringBuilder systemOutput;
@Before
public void setUp() {
systemOutput = injectSystemOutput();
}
@Test
public void testOut() {
OutDemo out = new OutDemo();
out.print("123");
Assert.assertEquals(systemOutput.toString(), "123");
}
private StringBuilder injectSystemOutput() {
StringBuilder stringBuilder = new StringBuilder();
PrintStream outputPrintStream = new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
stringBuilder.append((char) b);
}
});
System.setOut(outputPrintStream);
return stringBuilder;
}
}