2

So here is the code:

public int foo(InputStream in) {
    int counter = 0;
    Scanner scanner = new Scanner(in);
    while(scanner.hasNextLine()) {
        counter++;
        scanner.nextLine();
    }
    return counter;
}

Normally I will be passing a FileInputStream to this method, however I want to be able to test it without accessing a physical file.

Should I mock the File object? How to I implement

@Test
public void shouldReturnThree(){

}
Malt
  • 28,965
  • 9
  • 65
  • 105
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
  • 2
    How about a [`ByteArrayInputStream`](http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html)? – RealSkeptic Mar 09 '15 at 21:29

1 Answers1

5

You can pass a test String into the method as an InputStream like this (:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes());

(Shamelessly stolen from this answer)

For instance, this code will print 3:

String str = "\n\n\n";
InputStream stream = new ByteArrayInputStream(str.getBytes());
System.out.println(foo(stream));
Community
  • 1
  • 1
Malt
  • 28,965
  • 9
  • 65
  • 105