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.

8
  • i have tagged junit aswell tomake it more appropriate .. :) Commented Nov 3, 2012 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. Commented Nov 3, 2012 at 19:19
  • @VictorSorokin Can u pls illustrate by an example? Commented Nov 3, 2012 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. Commented Nov 3, 2012 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 Commented Nov 3, 2012 at 19:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.