2013-10-30 135 views
0

Java項目的Java項目的測試方法需要輸入

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); 
     } 

我想知道如何測試在測試類,要求用戶輸入這樣的方法。 的方法調用從ArrayLinearList其他方法和傳遞數據的用戶在進入,我想創建一個模擬了用戶可能輸入的代碼。

+1

http://stackoverflow.com/questions/6415728/junit-testing-with-simulated-user-input – xyz

回答

0

使用System.setIn爲Unitesting Scanner。例如:

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

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

輸出:

Your input data 
1

您可以使用框架,如的MockitoPowermock到嘲笑掃描儀。如果這個類然後調用掃描器輸入,你可以讓你的模擬器返回一些字符串,這些字符串將作爲你的類的用戶輸入處理。你的班級不會看到「真實」掃描儀和你的模擬實現之間的區別。

參見:

1

您可以使用System.setIn(InputSteam)

在這裏,您可以指定自己的InputStream和添加要它的輸入。