模拟给定输入的JUnit输出

时间:2017-10-24 06:03:47

标签: junit system-rules

public void MyTest {
 @Rule
   public final TextFromStandardInputStream systemInMock
  = emptyStandardInputStream();

 @Test
 public void shouldTakeUserInput() {
    systemInMock.provideLines("add 5", "another line");
     InputOutput inputOutput = new InputOutput();
    assertEquals("add 5", inputOutput.getInput());
 }
}

在这里,我想检查输入add 5我的输出应该在某些方法中使用System.out.println()语句的某些语句。是否可以模拟输出语句?

1 个答案:

答案 0 :(得分:3)

您可以使用SystemOutRule将输出写入System.out并对其进行断言:

public class MyTest {
    @Rule
    public final TextFromStandardInputStream systemInMock = 
        emptyStandardInputStream();

    @Rule
    public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();

    @Test
    public void shouldTakeUserInput() {
        systemInMock.provideLines("add 5", "another line");

        MyCode myCode = new MyCode();
        myCode.doSomething();

        assertEquals("expected output", systemOutRule.getLog());
    }
}