Search code examples
javaunit-testinginputstreamfileinputstream

How can I unit test a method that uses a Scanner and an InputStream?


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(){

}

Solution

  • 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));