I have a program that needs to process data from Standard-In. I can call it on the command line like so java program < input. I want to write a proper unit test for its main(). Is it possible to reassociate a method’s System.in with some other stream?
In the test, I can read the sample data, and then somehow run the original program with its stdin connected to some stream that i define (from the sample data) and verify that it returns what i expect. I considered using these classes:
PipedInputStream and
PipedOutputStream. But it would require me to modify the original program to read from a PipedInputStream every time I test it. Or I can isolate the stream reading into a function (eg. parseStream(InputStream) ) and pass a PipedInputStream which is already connected to the sample data.
I can also write a shell script to pipe whatever i want into its stdin, but the method in question will be a part of a series of processing steps so it shouldn’t itself write to stdout and actually returns ArrayList<SomeCompositeType>. Where SomeCompositeType contains the data that was read in a structured way (eg. some ints, arrays, Maps, etc..)
So is it possible to call some method that reads from System.in with a different stream?
See my comment.
What you appear to want is provided by
System.setIn🙂