从 JUnit 测试确认 FileReader 已正确关闭
我正在编写一些 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为做到这一点的方法是将 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.
一种可行的方法是在关闭 FileReader 后测试 read() 方法,这应该会引发异常。 例如:
One way that should work is to test the ready() method after you close your FileReader which should throw an exception. For example:
如果您可以将 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.