how to accept input from user in Junit console

2019-04-30 20:02发布

问题:

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.