2012-11-03 26 views
5

我想寫JUnit測試案例的功能:如何接受來自用戶的輸入在JUnit控制檯下面給出

class A{ 
    int i; 
    void set() 
    { 
    Scanner in=new Scanner(System.in); 
    i=in.nextInt(); 
    } 
} 

現在我的問題是,當我爲它創建一個JUnit測試的情況下,它不除用戶輸入外:

public void testSet() throws FileNotFoundException { 
    System.out.println("set"); 
    A instance = new A(); 
    int i=1; 
    instance.set(i); 
    // TODO review the generated test code and remove the default call to fail. 
    //fail("The test case is a prototype."); 
} 

請注意我應該做些什麼來接受用戶的輸入。

+0

我已標記爲junit以及更合適.. :) – PermGenError

+0

@ chaitanya10感謝 – user1778824

+2

您不需要用戶在JUnit測試中的輸入。如果您需要使用某個'InputStream'進行測試,請將其附加到'OutputStream'並以編程方式輸入輸入。 –

回答

7

您可以使用System.setIn()來模擬用戶輸入:

String inputData = "user input data"; 
System.setIn(new java.io.ByteArrayInputStream(inputData.getBytes())); 

現在,如果你打電話給你set()方法它會從你的字符串,而不是從標準輸入讀取數據。