Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to accept input from user in Junit console

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.

like image 407
user1778824 Avatar asked Nov 03 '12 19:11

user1778824


1 Answers

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.

like image 115
DaoWen Avatar answered Nov 14 '22 23:11

DaoWen