2012-07-25 115 views
1

我正在做测试驱动的开发,它要求我为从用户接收输入的类编写测试函数。由于控制台输入函数在测试期间停止输入,我使用一个使用字符串的InputStream编写测试。来自InputStream的扫描仪输入

String str="3\n2\n1\n4\n"; 
InputStream is = new ByteArrayInputStream(str.getBytes()); 
assertTrue(app.RunApp(is)); 

这导致调用函数getChoice(InputStream i),该函数涉及来自Scanner的控制台输入。

public int getChoice(InputStream i) throws IOException { 
     Scanner s=new Scanner(i); 
     s.useDelimiter("\n"); 
     String y= s.next(); 
     int x=Integer.parseInt(y); 
     return x; 
    } 

我希望上面的代码将字符串中的数字一个接一个。但是,正在发生的事情是,它会正确使用第一个数字,然后,流的位置将直接导向流的末尾,从而导致NoSuchElementException。请帮忙!

回答

0

使用...

String y = s.nextLine(); // That will take the entire line instead of only 1st word