Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test java programs that read from stdin and write to stdout

I am writing some code for a programming contest in java. The input to the program is given using stdin and output is on stdout. How are you folks testing programs that work on stdin/stdout? This is what I am thinking:

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

void printAverage(InputStream in, PrintStream out)

Now, I would like to test this using junit. I would like to fake the System.in using a String and receive the output in a 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 'correct' way to implement getInputStreamFromString() and getPrintStreamForString()?

Am I making this more complicated than it needs to be?

like image 863
user674669 Avatar asked Nov 11 '12 07:11

user674669


People also ask

How do you use stdin and stdout in Java?

Most HackerRank challenges require you to read input from stdin (standard input) and write output to stdout (standard output). Alternatively, you can use the BufferedReader class. In this challenge, you must read integers from stdin and then print them to stdout. Each integer must be printed on a new line.

How do you input stdin and stdout?

To give input we use the input stream and to give output we use the output stream. One popular way to read input from stdin is by using the Scanner class and specifying the Input Stream as System.in. For example: Scanner scanner = new Scanner(System.in); String userString = scanner.

How do you test methods in Java?

write a main method on your class, and call your test method. To check by running just write a main method and call this method with arguments. If you want to have a test case, take a look at JUnit or Mokito to write a test. There should be a way to run parts or the code without writing a main method or a test-class.


1 Answers

Try the following:

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

stringStream is a stream that will read chars 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 the outputStream which in turn will be able to return a string.

like image 107
Mihai Toader Avatar answered Oct 05 '22 08:10

Mihai Toader