1
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()在某些方法中使用语句的某些语句。是否可以模拟输出语句?

4

1 回答 1

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());
    }
}
于 2017-10-24T06:14:22.213 回答