Simulating System.in Testing with JUnit
In the realm of software testing, one often faces the challenge of simulating user input when dealing with command-line programs. When a program prompts for input via System.in, how does one automate this behavior in JUnit tests?
Solution
To bypass System.in and inject simulated user input, follow these steps:
Switch System.in Dynamically:
Use Java 8 streams to manipulate the System.in stream. For instance:
<code class="java">String data = "Hello, World!\r\n"; InputStream stdin = System.in; try { System.setIn(new ByteArrayInputStream(data.getBytes())); Scanner scanner = new Scanner(System.in); System.out.println(scanner.nextLine()); } finally { System.setIn(stdin); }</code>
The above is the detailed content of How Can You Simulate User Input in JUnit Tests for Command-Line Programs?. For more information, please follow other related articles on the PHP Chinese website!