how to accept input from user in Junit console

南楼画角 提交于 2019-12-07 05:06:19

问题


I am trying to write Junit test case for the function given below:

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

Now my problem is when i create a Junit test case for it, it does not except input from user:

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

Please suggets what should i do to accept input from user.


回答1:


You can use System.setIn() to mock user input:

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

Now if you call your set() method it will read the data from your string rather than from standard input.



来源:https://stackoverflow.com/questions/13212568/how-to-accept-input-from-user-in-junit-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!