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?
There's no API for determining whether a stream has been closed. Applications should be (and generally are) designed so it isn't necessary to track the state of a stream explicitly. Streams should be opened and reliably closed in an ARM block, and inside the block, it should be safe to assume that the stream is open.
You do need to close the input Stream, because the stream returned by the method you mention is actually FileInputStream or some other subclass of InputStream that holds a handle for a file. If you do not close this stream you have resource leakage.
To perform unit testing, we need to create test cases. The unit test case is a code which ensures that the program logic works as expected. The org. junit package contains many interfaces and classes for junit testing such as Assert, Test, Before, After etc.
If I understood the task correctly it could be like this
static boolean isClosed;
public void run() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file) {
@Override
public void close() throws IOException {
isClosed = true;
super.close();
}
};
// more stuff here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With