Reputation: 198198
There is such a method which read a file and do something:
public void readFileAndDoSomething(File file) {
InputStream inputStream = new FileInputStream(file);
// a lot of complex code which reads the inputStream
// and we don't know if the inputStream is closed or not
}
Now I want to test the method to make sure if any input stream that uses the file is closed or not finally.
My test code:
public void test() {
File testFile = new File("my_test_file");
readFileAndDoSomething(testFile);
// is it possible to just check the file to make sure
// if it is still used by some unclosed input streams?
}
Please see my comment in the test
method, is it possible?
Upvotes: 1
Views: 198
Reputation: 27844
To make this testable, you should pass in an InputStream
instead of a File
.
That way you can either close the InputStream
yourself, or write a test that passes in a mock InputStream
and verifies that the method closed it.
public void readStreamAndDoSomething(InputStream inputStream) {
// a lot of complex code which reads the inputStream
// and we don't know if the inputStream is closed or not
}
public void clientCode(File file) {
InputStream inputStream = new FileInputStream(file);
readStreamAndDoSomething(inputStream);
inputStream.close();
}
Upvotes: 1
Reputation: 36339
It is possible at least in LINUX, though not directly in Java.
LINUX has a utility called lsof
that can tell whether a given file is open in some process. You can call this utility with Runtime.exec or ProcessBuilder.
In Windows, I'm not sure, but couldn't you try to open the file for writing? It should not work if there is still someone having that file open.
Upvotes: 1