![JAR search and dependency download from the Maven repository](/logo.png)
org.junit.contrib.java.lang.system.TextFromStandardInputStream Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of system-rules Show documentation
Show all versions of system-rules Show documentation
A collection of JUnit rules for testing code which uses java.lang.System.
package org.junit.contrib.java.lang.system;
import static java.lang.System.in;
import static java.lang.System.setIn;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.junit.rules.ExternalResource;
/**
* The {@code TextFromStandardInputStream} rule replaces {@code System.in} with
* another {@code InputStream}, which provides an arbitrary text. The original
* {@code System.in} is restored after the test.
*
*
* public void MyTest {
* @Rule
* public final TextFromStandardInputStream textFromStandardInputStream
* = new TextFromStandardInputStream("foo");
*
* @Test
* public void readTextFromStandardInputStream() {
* BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
* assertEquals("foo", reader.readLine());
* }
* }
*
*/
public class TextFromStandardInputStream extends ExternalResource {
private final String text;
private InputStream originalIn;
public TextFromStandardInputStream(String text) {
this.text = text;
}
@Override
protected void before() throws Throwable {
originalIn = in;
InputStream is = new ByteArrayInputStream(text.getBytes());
setIn(is);
}
@Override
protected void after() {
setIn(originalIn);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy