One common way to test similar code would be to extract a method that uses a scanner and PrintWriter similar to this StackOverflow answer , and verify that:
public void processUserInput() { processUserInput(new Scanner(System.in), System.out); } public void processUserInput(Scanner scanner, PrintWriter output) { output.println("Give a number between 1 and 10"); int input = scanner.nextInt(); while (input < 1 || input > 10) { output.println("Wrong number, try again."); input = scanner.nextInt(); } return input; }
Please note that you will not be able to read your output to the end, and you will need to indicate all your data in front:
@Test public void shouldProcessUserInput() { StringWriter output = new StringWriter(); String input = "11\n" // "Wrong number, try again." + "10\n"; assertEquals(10, systemUnderTest.processUserInput( new Scanner(input), new PrintWriter(output))); assertThat(output.toString(), contains("Wrong number, try again."));); }
Of course, instead of creating an overload method, you can also save the “scanner” and “output” as mutable fields in the system under test. As a rule, I prefer to keep classes as stateless as possible, but this is not a very big concession if it is important for you or your staff / instructors.
You can also put your test code in the same Java package as the test code (even if it is in a different source folder), which allows you to reduce the visibility of two parameter overloads that must be private to the package.
Jeff Bowman Apr 29 '14 at 3:11 2014-04-29 03:11
source share