Test java programs that read from stdin and write to stdout

后端 未结 3 1613
误落风尘
误落风尘 2020-12-11 03:38

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

3条回答
  •  一生所求
    2020-12-11 04:01

    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?

    Another way to send characters to System.in is to use PipedInputStream and PipedOutputStream. Maybe something like the following:

    PipedInputStream pipeIn = new PipedInputStream(1024);
    System.setIn(pipeIn);
    
    PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
    
    // then I can write to the pipe
    pipeOut.write(new byte[] { ... });
    
    // if I need a writer I do:
    Writer writer = OutputStreamWriter(pipeOut);
    writer.write("some string");
    
    // call code that reads from System.in
    processInput();
    

    On the flip side, as mentioned by @Mihai Toader, if I need to test System.out then I do something like:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos));
    
    // call code that prints to System.out
    printSomeOutput();
    
    // now interrogate the byte[] inside of baos
    byte[] outputBytes = baos.toByteArray();
    // if I need it as a string I do
    String outputStr = baos.toString();
    
    Assert.assertTrue(outputStr.contains("some important output"));
    

提交回复
热议问题