I have a Runnable along the lines of:
public void run() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
//more stuff here
}
catch (Exception e) {
//simplified for reading
}
finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
}
How do I test inputStream.close() was invoked? I am currently using Mockito and JUnit. I know injecting the inputStream in is an idea, but I don’t want the resources to be used until run?() is called, hence it being a local variable. So how can I redesign my code in a way that allows me to test whether close was called?
As there is no reason to expose the InputStream outside of the scope of this method you have a testing problem.
But I assume you don’t directly care about the
InputStreambeing closed. You want to test that because you’ve been told it’s good practice (and it is). But I think what you actually care about is the negative impact of the stream being left open. What is the effect?Try modifying this method so it does not close the stream, then execute it many times over. Do you get a memory leak, or run out of file handles or some other tomfoolery? If so, you have a reasonable test.
Alternatively, just go ahead and expose a decorated InputStream that can tell you if it has been closed or not. Make it package protected. That’s the “impure”, but pragmatic approach.