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());
 }
}

Here, I want to check for the input add 5 my output should some statement using System.out.println() statement within some method. Is It possible to simulate output statement?

Mureinik
  • 297,002
  • 52
  • 306
  • 350

1 Answers1

3

You can use the SystemOutRule to get the output written to System.out and assert against it:

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());
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • myCode.doSomething() is using println(), when try to get through getLog test case is not passed, If I use print method it's getting pass – Sasireka Ganesan Oct 24 '17 at 06:53
  • @SasirekaGanesan `println` adds a newline to the output. If you use it, you should assert against `"expected output\n"`. – Mureinik Oct 24 '17 at 07:34