Class TextFromStandardInputStream

java.lang.Object
org.junit.rules.ExternalResource
org.junit.contrib.java.lang.system.TextFromStandardInputStream
All Implemented Interfaces:
org.junit.rules.TestRule

public class TextFromStandardInputStream extends org.junit.rules.ExternalResource
The TextFromStandardInputStream rule replaces System.in with another InputStream, which provides an arbitrary text. The original System.in is restored after the test.
  public void MyTest {
    @Rule
    public final TextFromStandardInputStream systemInMock
      = emptyStandardInputStream();

    @Test
    public void readTextFromStandardInputStream() {
      systemInMock.provideLines("foo", "bar");
      Scanner scanner = new Scanner(System.in);
      scanner.nextLine();
      assertEquals("bar", scanner.nextLine());
    }
  }

Throwing Exceptions

TextFromStandardInputStream can also simulate a System.in that throws an IOException or RuntimeException. Use

   systemInMock.throwExceptionOnInputEnd(IOException)

or

   systemInMock.throwExceptionOnInputEnd(RuntimeException)

If you call provideLines(String...) in addition then the exception is thrown after the text has been read from System.in.