JUnit test for console input and output

前端 未结 2 480
说谎
说谎 2020-12-21 13:19

I have only one method main. How to check System.out.println() and replace Scanner to input values automatically using JUnit?

P.S. Please, provide some solutions...

2条回答
  •  隐瞒了意图╮
    2020-12-21 14:06

    Ideally, extract the awkward dependencies so that you can test without them. Change main to simply:

    public static void main(String[] args) {
      doWork(new Scanner(System.in), System.out);
    }
    
    // TODO: Rename to something meaningful
    public static void doWork(Scanner input, PrintStream output) {
      // Remainder of code
    }
    

    (Consider using a Writer instead of a PrintStream for output.)

    Then you don't really need to unit test main - but you can test doWork using a Scanner based on a StringReader, and output based on a StringWriter, providing whatever input you want and checking the output.

提交回复
热议问题