You can mock the the inputstream using something like Mockito. But it can also be done without this. Using System.setIn()
you can change the stream that System.in
will return.
public class ReaderTest {
@Test
public void test() throws IOException {
String example = "some input line"; //the line we will try to read
InputStream stream = new ByteArrayInputStream((example+"\n").getBytes(StandardCharsets.UTF_8)); //this stream will output the example string
InputStream stdin = System.in; //save the standard in to restore it later
System.setIn(stream); //set the standard in to the mocked stream
assertEquals(example, Reader.readLine()); //check if the method works
System.setIn(stdin);//restore the stardard in
}
}
class Reader{
public static String readLine() throws IOException{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
return stdin.readLine();
}
}
Another advantage of mocking the stream is that you don't have to enter the String anymore everytime you want to run the test.
Also note that restoring System.in
can be done in a before and after method if you plan on doing this a lot.