GBP
GBP

Reputation: 412

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.

Upvotes: 1

Views: 3594

Answers (2)

superfav
superfav

Reputation: 1061

You could replace the new ByteArrayInputStream(bytes) by a method that creates and returns an InputStream from a byte array. If you create an interface for that, lets say

interface InputStreamFactory {
  InputStream from(byte[] bytes);
}

Then you can have an implementation that returns a ByteArrayInputStream for production code and one that returns an object that throws IOException for the test. And maybe someday a BufferedInputStream one, and so on.

private final InputStreamFactory factory;

[...]

public void readFile(byte[] bytes) {    
    try (final InputStream inputStream = factory.from(bytes)) {
    ...

Upvotes: 1

tddmonkey
tddmonkey

Reputation: 21184

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
}

Upvotes: 3

Related Questions