2

I have to test someone elses method that runs endlessly but asks for an input:

public void automatize()
{
    String cadena = new String();

    while(true)
    {
        System.out.println("Executing...(Enter command)");
        System.out.println("Enter Q to exit");
        Scanner sc= new Scanner(new InputStreamReader(System.in));
        cadena=sc.nextLine();
        if(cadena.toLowerCase().equals("q"))
            break;
        String[] command = str.split(" ");
        if(comando.length!=0)
            new Extractor().run(command);
    }
}

How am I supposed to test this with JUnit?

This is what I've tried to do, but, well, It doesn't actually do anything:

@Test
public void testAutomatize_q() {
    ByteArrayInputStream in = new ByteArrayInputStream("Q".getBytes());
    System.setIn(in);

    extractor.automatize();

    System.setIn(System.in);
}
Sufian
  • 6,405
  • 16
  • 66
  • 120
Ikzer
  • 527
  • 11
  • 29

2 Answers2

2

You can replace System.in with you own stream by calling System.setIn(InputStream in). Input stream can be byte array:

ByteArrayInputStream in = new ByteArrayInputStream("My string".getBytes());
System.setIn(in);

// do your thing

// optionally, reset System.in to its original
System.setIn(System.in)

Different approach can be make this method more testable by passing IN and OUT as parameters:

public static int testUserInput(InputStream in,PrintStream out) {
   Scanner keyboard = new Scanner(in);
    out.println("Give a number between 1 and 10");
    int input = keyboard.nextInt();

while (input < 1 || input > 10) {
    out.println("Wrong number, try again.");
    input = keyboard.nextInt();
}

return input;
}

Taken from here: JUnit testing with simulated user input

Community
  • 1
  • 1
Luke SpringWalker
  • 1,600
  • 3
  • 19
  • 33
1

You could use a framework like Mockito in order to mock the Scanner object, and return a fix value when sc.nextLine() is called. Here's a link of mockito http://mockito.org/, see the 'how' menu to have some examples.

vincent
  • 1,214
  • 12
  • 22