0

Java Project

   public ArrayShoppingList()
   {

    // initialise instance variables
     super();
    }

   //public void addItem(int itemPosition,String item){
    // super.add(itemPosition,item);
    //  }
   public void addItem(){
      System.out.println("Please enter the item you wish to enter into the shopping 
       List");
       Scanner reader1 = new Scanner(System.in);
       String item = reader1.next();
       super.add(super.size(),item);
      }

    public void getPosition(){
     System.out.println("Please enter the item name that you wish to find 
     theposition         of");
    Scanner reader1 = new Scanner(System.in);
    String item = reader1.next();
    super.indexOf(item);
    }



 public void removeItem(){
    System.out.println("Please enter the item number that you wish to remove");
    Scanner reader1 = new Scanner(System.in);
    String item = reader1.next();
    int itemIndex = super.indexOf(item);
    super.remove(itemIndex);
       }

I want to know how to test such methods in a Test Class that ask for user input. The methods call other methods from an ArrayLinearList and pass data that the user has entered in. I want to create code that simulates what the user might enter in.

noone
  • 19,520
  • 5
  • 61
  • 76

3 Answers3

1

You can use frameworks like Mockito or Powermock to mock the Scanner. If the class then calls the Scanner for input, you can let your mock return some strings which will be handled as user input by your class. Your class will not see a difference between the "real" scanner and your mock implementation.

See also:

L.Butz
  • 2,466
  • 25
  • 44
1

You can use System.setIn(InputSteam)

Here you can specify your own inputstream and add the input you want to it.

Plux
  • 414
  • 4
  • 15
0

Use System.setIn for Unitesting Scanner. For example:

 String input = "Your input data";
 System.setIn(new ByteArrayInputStream(input.getBytes()));

Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());

Output:

Your input data
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225