0

method written in my class

public static Advertisement[] createAd() throws IOException
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    Advertisement[] ad = new Advertisement[5];
    int count =0;
    char ch;
    do
    {
    System.out.println("Enter advertisement id:");
    int id=Integer.parseInt(br.readLine());
    System.out.println("Enter advertisement type:");
    String type=br.readLine();
    ad[count]= new Advertisement(id, type);
    count++;
    System.out.println("Do you want publish another   advertisement(Y/N):");
     ch = br.readLine().charAt(0);

    if((ch!='y')&&(ch!='Y'))
    {
        break;
    }

    }while(count<=5);
    if(count==5)
    {
        System.out.println("Maximum ads reached");
        return ad;
    }
    return ad;
}


Juint @Test method
 @Test
public void testCreateAd() throws IOException
{
    Advertisement[] a = Advertisement.createAd();
    assertTrue("Maximum five ads only should be created",(a.length<=5));
}

I want to check, createAd method should return max of 5 object of the type Advertisement. But when @Test method is running it's asking input, can we pass input to those readLine method through some where

  • The thing to look at: https://stackoverflow.com/a/6416591/1531124 . Thing is: you *can* test code that reads from System.in using some tricks. But: you shouldn't do so. You completely *hide* the fact that your code is normally reading from stdin from your production code. So that it works with *any* kind of input. – GhostCat Oct 12 '17 at 11:28

2 Answers2

0

I think you need to mock the buffered reader. you can pass it as a method parameter (or create another method that accept it as parameter, and then Mock it in you test code. have a look to this.

marco
  • 671
  • 6
  • 22
0

BufferedReader should be a private class member. If you do this you can @Mock this member in you testclass and then you can control every call of it and the returning values.

@Mock
private BufferedReader bufferedReaderMock;

Mockito.doReturn("some input").when(bufferedReaderMock).readLine();

Now you can control and simulate values a user maybe entered. don´t forget this before yoz´re asserting:

Mockito.verify(bufferedReaderMock).readLine(); // Verify it was called
Mockito.verifyNoMoreInteractions(<all mocks)); // verify no other dependency class/member was called.
LenglBoy
  • 1,451
  • 1
  • 10
  • 24