Using JUnit to test a main method that requires simulation of keyboard input with an input stream?

后端 未结 2 1326
北海茫月
北海茫月 2021-01-15 09:03

Let\'s suppose I have a program with a main method that uses the java.util.Scanner class to receive user input.

import java.util.Scanner;

publ         


        
2条回答
  •  醉梦人生
    2021-01-15 09:48

    You can redirect System.out, System.in, and System.err like this:

    System.setOut(new PrintStream(new FileOutputStream("output")));
    
    System.setErr(new PrintStream(new FileOutputStream("error")));
    
    System.setIn(new FileInputStream("input"));
    

    So in you unit test you can setup this redirection and run your class.

提交回复
热议问题