0

I gotta to test method that is responsible for taking input. It contains try/catch blocks. Should I unit test? If so, how to do it?

static String takeStringInput(Scanner input, String label) {
    while (true) {
        try {
            System.out.println(label + ": ");
            return input.next();
        } catch (InputMismatchException e) {
            System.out.println("Try again, bad input");
            input.next();
        }
    }
}

Mocking Scanner is impossible as no possible to mock final class.

must
  • 27
  • 7
  • [It is impossible to answer your question because you do not provide a specification of what your code ought to do](https://stackoverflow.com/a/53757321/545127). – Raedwald Dec 13 '18 at 09:13

1 Answers1

0

Mock the Scanner (perhaps using Mockito) to return a valid value. This will test the "happy path." Then, modify the mock so that it returns an exception and then a valid value.

Steve11235
  • 2,849
  • 1
  • 17
  • 18
  • Something like this: `@Test void takeStringInput() { Scanner scanner = mock(Scanner.class); when(scanner.next()).thenReturn("test"); InputTakers.takeStringInput(scanner,"brand"); }` ? unfortunately error appear `Cannot mock/spy class java.util.Scanner Mockito cannot mock/spy because : - final class` – must Aug 23 '18 at 14:57