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?