从 JUnit 测试确认 FileReader 已正确关闭

发布于 2024-07-10 16:54:12 字数 247 浏览 5 评论 0原文

我正在编写一些 Java 代码,它使用 FileReader 从一些输入文件加载数据。 我非常频繁地使用 TDD,并且我想添加一些测试,以确保在完成后通过在阅读器上调用 close() 来正确清理。 不幸的是,我无法想出一个好的方法来测试这一点。 有人有任何见解吗?

编辑添加:我知道我可以使用模拟对象显式测试关闭调用,但如果可能的话我想避免它,部分是因为我发现它们会导致代码更脆弱,部分是因为我很好奇是否可能编写可以识别不关闭文件的影响的代码。)

I'm writing some Java code that uses a FileReader to load data from a few input files. I'm using TDD pretty heavily, and I'd like to add some tests that ensure that I'm cleaning up properly by calling close() on the reader when I'm done with it. Unfortunately, I can't come up with a good way to test for this. Anyone have any insights?

Edited to add: I know I can test explicitly for the close call using mock objects, but I'd like to avoid it if possible, partly because I find they lead to somewhat brittler code, and partly because I'm curious whether it's possible to write code that can recognize the effects of not closing a file.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

迟月 2024-07-17 16:54:12

我认为做到这一点的方法是将 FileReader 或创建 FileReader 的工厂注入到您的类中。 然后在单元测试中,您可以注入 FileReader 的模拟版本,并检查是否已调用其正确的方法。 您可能需要查看 JMock 来创建模拟 FileReader 并设置 close 方法调用的期望。

I think the way to do this is to inject the FileReader, or a Factory that creates the FileReader, into your class. Then in your unit test you can inject a mock version of the FileReader and check that the proper method on it has been called. You might want to look at JMock to create the mock FileReader and set up the expectation for the close method call.

我纯我任性 2024-07-17 16:54:12

一种可行的方法是在关闭 FileReader 后测试 read() 方法,这应该会引发异常。 例如:

FileReader fr = new FileReader("somefile");
// ... file reader activity
fr.close();

// After closing the reader, the ready() method should cause an IOException:
boolean isOpen = true;
try {
  isOpen = fr.ready();
} catch (IOException e) {
  isOpen = false;
}
assertFalse("FileReader is still open", isOpen);

One way that should work is to test the ready() method after you close your FileReader which should throw an exception. For example:

FileReader fr = new FileReader("somefile");
// ... file reader activity
fr.close();

// After closing the reader, the ready() method should cause an IOException:
boolean isOpen = true;
try {
  isOpen = fr.ready();
} catch (IOException e) {
  isOpen = false;
}
assertFalse("FileReader is still open", isOpen);
川水往事 2024-07-17 16:54:12

如果您可以将 FileReader 对象传递给调用,那么您可以提供一个具有重写的 close 方法的自定义 FileReader - 在该方法中,您有一个布尔变量来检查是否关闭。 然后您可以将其用于单元测试。

If you can pass the FileReader object in to the call then you can provide a custom FileReader that has an overridden close method -- in that, you have a boolean variable that checks on closed or not. You can then use that for your unit test.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文