First of all, to be able to test things right you have to learn what what loose coupling is and what Mock Objects are.
Basically, it is never a good idea to create an object with new
because you create a hard dependency between the class InputStreamReader
and your logic.
If your object p
implements some kind of an interface, it would be good if you pass the instance of it from outside of your logic. Some implementations of Mock Objects also allow you to mock a class but I would not recommend that.
For example if you write your code like that:
public myMethod(SomeKindOfInterface p, InputStreamReader reader) {
try {
p.load(reader);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch(IOException e) {
//intentionally left blank, nothing could be done upon exception on closing
}
}
}
Then in your JUnit you could use Mockito to mock the IOException
.
InputStreamReader reader = new InputStreamReader(WsdlSource.class.getClassLoader().getResourceAsStream("stringresources/stringresources.properties"), "UTF-8");
SomeKindOfInterface mock = Mockito.mock(SomeKindOfInterface.class);
Mockito.when(mock.load(reader)).thenThrow(new IOException());
myInstance.myMethod(mock, reader);
This way you would have your catch
block covered.