5

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.

user1778824
  • 369
  • 2
  • 6
  • 15
  • i have tagged junit aswell tomake it more appropriate .. :) – PermGenError Nov 03 '12 at 19:17
  • 2
    You don't need input from user in JUnit tests. If you need to test with some `InputStream`, attach it to your `OutputStream` and feed input programmatically. – Victor Sorokin Nov 03 '12 at 19:19
  • @VictorSorokin Can u pls illustrate by an example? – user1778824 Nov 03 '12 at 19:20
  • Really, you should design your code so that any code under test doesn't need to read from `System.in`, but instead reads from a passed-in `InputStream` or the like. – Louis Wasserman Nov 03 '12 at 19:21
  • 1
    i know but that's my requirement..is there no way to enter input from user ...and test the method using Junit – user1778824 Nov 03 '12 at 19:25
  • The purpose of using JUnit is for performing automated tests. IMO, what you are trying to achieve is against that purpose. You should be creating some test-fixtures instead. – Bhesh Gurung Nov 03 '12 at 19:26
  • but i really need to test a method which takes input from user...is there no way by which i can achieve this? – user1778824 Nov 03 '12 at 19:29
  • While @Victor's suggestion is the best option for your need, data could be fed into testcases through the DataProviders of TestNG. And porting testcases from JUnit to TestNG requires very little effort. – Arun Manivannan Nov 03 '12 at 19:40

1 Answers1

7

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.

DaoWen
  • 32,589
  • 6
  • 74
  • 101