0

I created a method that uses a scanner object and then I want to create a test for that method. But soon as I run the test it just stops when it asks for your input to input into the console but i cant enter anything because it is a test method so how can I simulate a keyboard input in my tester method . Im inputting the values into a Hashmap

Main mehtod

public void addValue() {
        System.out.println("Type the key value that you want to add");
        Scanner keyb = new Scanner(System.in);
        String key = keyb.next();
        System.out.println("Type in the name Value");
        String value = keyb.next();
        mapExample.put(key, value);

    }

Test method

void addValue() {
        MapImplement mapTestO =new MapImplement();
        mapTestO.addValue();
        String mapValue=mapTestO.mapExample.get("KeyTest1");
        assertEquals("ItemTest1",mapValue);
        mapTestO=null;

    }
Dunmol
  • 41
  • 4
  • Maybe this helps: https://stackoverflow.com/questions/31635698/junit-testing-for-user-input-using-scanner – Daniel May 10 '21 at 11:41

1 Answers1

4

You problem is not using Scanner but that the input is coming from standard input (System.in). You should refactor the method to receive the input stream as a parameter. In that way you can send different inputs in the tests and avoid reading from standard input (console) when testing.

Example:

public void addValue(InputStream is) {
        Scanner keyb = new Scanner(is);
        String key = keyb.next();
        String value = keyb.next();
        mapExample.put(key, value);
}

Note that unit testing is expected to run in an automated way and not require user intervention, like writing the input manually.

aled
  • 21,330
  • 3
  • 27
  • 34