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

后端 未结 2 1333
北海茫月
北海茫月 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:37

    The System Rules library provides JUnit rules for such tests. Additionally you should use a parameterized test.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题