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:
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);
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3