模拟给定输入的 JUnit 输出

Simulation of JUnit output for the given input

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() 语句的某些语句。是否可以模拟输出语句?

您可以使用 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());
    }
}