GBP GBP - 1 month ago 18
Java Question

Unit test IOException for InputStream

Is there a way to unit test the following code without using PowerMock? We have sonar unit test code coverage and it does not recognise code tested via PowerMockRunner. So I was looking for a way to simulate IOException or use Mockito somehow to test this code so that it throws exception.

public void readFile(byte[] bytes) {
try (final InputStream inputStream = new ByteArrayInputStream(bytes)) {
.....
} catch (IOException e) {
throw new SystemException("Error reading file");
}
}



@Test(expected = SystemException.class)
public void testException {
}


Any suggestion would be great.

Thanks.

Answer

A ByteArrayInputStream will never throw an Exception so subsequently your try / catch is pointless. Just create the ByteArrayInputStream and use it directly and dump the exception handling. If you check the method signatures of ByteArrayInputStream you'll notice that the exceptions are removed so you don't have to worry about it.

Update:

You can safely interact with the ByteArrayInputStream like this:

public void readFile(byte[] bytes) {
    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
    ....
    // no need to close the inputStream as it's a NO-OP
}