如何在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."); } 

请建议我该怎么做才能接受用户的输入。

您可以使用System.setIn()来模拟用户输入:

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

现在,如果调用set()方法,它将从字符串而不是标准输入中读取数据。