Mocking a BufferedReader and an InputStream

Some times you may want to emulate reading multiple lines, this is how!

I have found two ways of mocking a input data for your Mockito tests.

First approach

The first method is lightweight and relatively simple to implement. Firstly in your unit test create a member variable by injecting a BufferReader

@Inject
private BufferedReader bufferedReader;@Spy InjectMocks
InstanceUnderTest instanceUnderTest;

Then define what happens when you read lines from the buffered reader

Mockito.when(bufferedReader.readLine())
    .thenReturn("The first line returned from the bufferedReader instance")
    .thenReturn("And this is the second line returned!")
    .thenReturn(null); 

We need to tell our class under test to return our mock when the getBufferedReader method is called

doReturn(bufferedReader).when(instanceUnderTest).getBufferedReader(Mockito.any());

Finally the code in our instanceUnderTest looks like this, when the getBufferedReader(file) method is called our mocked bufferedReader instance will be returned

try (BufferedReader br = getBufferedReader(file)) {
    for (String line; (line = br.readLine()) != null; ) {
        LOGGER.debug("Obtained '{}' from the buffered reader", line);    
    }
}

Second approach

This approach uses the apache commons IOUtils class (org.apache.commons.io.IOUtils), can be sourced from maven. Slightly less flexible but really easy to implement,

In the unit test method body define an InputStream instance like so

InputStream inputStream = IOUtils.toInputStream("This line of text is to be returned");

Now you need to tell your instance under test to get the mocked object when the getInputStream() method is called

doReturn(inputStream).when(instanceUnderTest).getInputStream();

Similarly to the first approach the instance under test has a getter for the input stream instance.

Tags:
Mockito
junit
BufferedReader

v1.9.1

© ScottFreeIT.com 2020