Check java programs that are read from stdin and write to stdout

I am writing code for a programming contest in java. The input to the program is set using stdin, and the output to stdout. How do you people test programs that run on stdin / stdout? That's what I think:

Since System.in is of type InputStream and System.out is of type PrintStream, I wrote my code in func with this prototype:

void printAverage(InputStream in, PrintStream out) 

Now I would like to test this with junit. I would like to fake System.in with String and get the output in String.

 @Test void testPrintAverage() { String input="10 20 30"; String expectedOutput="20"; InputStream in = getInputStreamFromString(input); PrintStream out = getPrintStreamForString(); printAverage(in, out); assertEquals(expectedOutput, out.toString()); } 

What is the β€œright” way to implement getInputStreamFromString () and getPrintStreamForString ()?

Am I making it more complicated than it should be?

+9
java junit mocking
Nov 11 '12 at 7:08
source share
2 answers

Try the following:

 String string = "aaa"; InputStream stringStream = new java.io.ByteArrayInputStream(string.getBytes()) 

stringStream is a stream that will read characters from the input string.

 OutputStream outputStream = new java.io.ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); // .. writes to printWriter and flush() at the end. String result = outputStream.toString() 

printStream is a printStream that will write to outputStream which, in turn, will be able to return a string.

+6
Nov 11 '12 at 7:21
source share

EDITED: Sorry, I misunderstood your question.

Reading with a scanner or buffer, the latter is much faster than the first.

 Scanner jin = new Scanner(System.in); BufferedReader reader = new BufferedReader(System.in); 

Write to stdout with a writer. You can also type Syso directly, but this is slower.

 System.out.println("Sample"); System.out.printf("%.2f",5.123); PrintWriter out = new PrintWriter(System.out); out.print("Sample"); out.close(); 
0
Nov 11 '12 at 7:13
source share



All Articles