0

I have to test a main method, I want to send stuff to System.in and then see what comes out of System.out.

I do it like this:

public class Check3_1 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        InputStream originalIn = System.in;
        PrintStream originalOut = System.out;

        String input = "steve\n";
        String expectedOutput = "Hello, steve";
        InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
//      BufferedInputStream bis = new
        ByteArrayInputStream bais = new ByteArrayInputStream(new byte[100]);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
        PrintStream ps = new PrintStream(baos);

        System.setIn(bais);
        System.setOut(ps);
        Homework_3.main(args);
        String output = baos.toString(StandardCharsets.UTF_8.name());

        System.setIn(originalIn);
        System.setOut(originalOut);

        System.out.println("actual output: "+output);
        System.out.println("correct?: "+output.equals(expectedOutput));

    }
}

Is there a better way to do it? Is there some trick that I can use so I can send stuff to input after I check some intermediary output? Probably an inputstream implementation I can use to send new lines all the time? And probably some printstream I can use to see some intermediary output?

mist
  • 1,853
  • 2
  • 19
  • 33

1 Answers1

0

The normal way to do this is to start a new process and read the output of the process while feeding it input. This allows you to run either a) more than one of these at once or b) use the console naturally in the testing party of the program.

To do this in process is to start a thread which generates input to the test code and another which reads it both using pipes.

How testing is normally done is via unit tests. You test components which take input for any source given to it (it could be System.in or an input the test provides) and your component makes callbacks (or in you must to an output you provide) There is a number of libraries to support checking that the callbacks create the expected events.

This way you can test the component in isolation, interactively in one thread, with very little overhead.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130