5

我正在尝试为下面给出的函数编写 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.");
}

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

4

1 回答 1

7

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

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

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

于 2012-11-03T19:48:01.907 回答