我有一个 Runnable
的行:
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) {}
}
}
}
如何测试 inputStream.close()
是否被调用?我目前正在使用 Mockito 和 JUnit。我知道注入(inject) inputStream
是一个想法,但我不希望在调用 run?()
之前使用资源,因此它是一个局部变量。那么我该如何重新设计我的代码以允许我测试是否调用了 close?
最佳答案
如果我正确理解任务,它可能是这样的
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
关于java - 我如何对这个 inputStream 进行单元测试已经关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13800269/