gpt4 book ai didi

java - 我如何对这个 inputStream 进行单元测试已经关闭?

转载 作者:搜寻专家 更新时间:2023-10-30 19:52:03 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com