如何在Junit控制台中接受来自用户的输入

use*_*824 5 java junit junit4 junit3

我正在尝试为下面给出的函数编写Junit测试用例:

class A{
  int i;
  void set()
  {
    Scanner in=new Scanner(System.in);
    i=in.nextInt();
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我的问题是当我为它创建一个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.");
}
Run Code Online (Sandbox Code Playgroud)

请建议我该怎么做才能接受用户的意见.

Dao*_*Wen 7

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

String inputData = "user input data";
System.setIn(new java.io.ByteArrayInputStream(inputData.getBytes()));
Run Code Online (Sandbox Code Playgroud)

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