I have a method which reads lines from the standard input and writes lines to the standard output.
From within a JUnit test, how can I send input to the method, and how can I capture its output so that I can make assertions on it?
Typically this is the keyboard, but you can specify that input is to come from a serial port or a disk file, for example. The standard output device, also referred to as stdout , is the device to which output from the system is sent. Typically this is a display, but you can redirect output to a serial port or a file.
The tee command, used with a pipe, reads standard input, then writes the output of a program to standard output and simultaneously copies it into the specified file or files. This gives you the advantage of viewing your output immediately and storing it for future use at the same time.
The readAll() method reads all remaining input on standard input and returns it as a string. As an example, the following code fragment reads all of the remaining tokens from standard input and returns them as an array of strings. String[] words = StdIn.
In computer programming, standard streams are interconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin), standard output (stdout) and standard error (stderr).
You should not have a method which reads from standard input and writes to standard output.
You should have a method which accepts as parameters the InputStream
from which it reads, and the PrintStream
into which it writes. (This is an application, at the method level, of a principle known as Dependency Injection (Wikipedia) which is generally used at the class level.)
Then, under normal circumstances, you invoke that method passing it System.in
and System.out
as parameters.
But when you want to test it, you can pass it an InputStream
and a PrintStream
that you have created for test purposes.
So, you can use something along these lines:
void testMyAwesomeMethod( String testInput, String expectedOutput )
{
byte[] bytes = testInput.getBytes( StandardCharsets.UTF_8 );
InputStream inputStream = new ByteArrayInputStream( bytes );
StringWriter stringWriter = new StringWriter();
try( PrintWriter printWriter = new PrintWriter( stringWriter ) )
{
myAwesomeMethod( inputStream, printWriter );
}
String result = stringWriter.toString();
assert result.equals( expectedOutput );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With