单元测试是否清理了非托管资源
我正在使用 TDD 并为使用非托管资源的 System.IO.Stream 对象创建单元测试。我的项目由许多这样的流组成,我想测试这些实现在处置它们时是否真正清理了它们的非托管资源。
知道我该怎么做吗?
今天早上我可能有点累,但我能想到的就是创建和处置 1k 实例并查看内存消耗。
我还必须考虑“如果它们不从 Read() 超时怎么办”,因此是否有一些通用的、超级神奇的测试流的方法可能是相关的。
I'm using TDD and creating unit tests for System.IO.Stream objects that use unmanaged resources. My project consists of many such streams and I want to test if the implementations actually clean up their unmanaged resources when they are disposed.
Any idea how I can do this?
I might just be a bit tired this morning, but all I can come up with is creating and disposing 1k instances and look at memory consumption.
I also have to think of "what if they don't timeout from Read()", so if there is some great universal super-fantastic way of testing streams that could be relevant.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
取决于资源是什么,但如果您将流保存到磁盘,并且您在没有清理的情况下编码失败,则尝试删除文件会导致问题。
然而,TTD 方法会导致异常,您的代码应该处理并抛出异常(首选但并非总是如此)。然后进行测试,将其作为预期异常,然后检查资源以查看它们是否已正确整理。这当然是对已知情况的测试,无论什么情况都比较困难。
我们也使用了很多流,但基本上我们遵循 FxCop 和最佳实践,编写了一些实用程序例程和帮助程序类。之后,它就虔诚地使用或实现 IDisposable。
我彻底推荐的另一件事是使用 FileStream 的“完整”版本来读取和写入磁盘。
你不会看到类似的东西,
相反,我们会
尽可能多地钉住未知的事物,如果你选择的神对你微笑,那么从务实和实际的意义上来说,这可能是所有这些。
Depends on what the resource is but if you was saving a stream to disk, and you code fellover without cleaning up, attempting to delete the file would cause a problem.
However a TTD approach would be to cause an exception, which your code should handle and throw (preferred but not always). Then have the test, pick it up as an expected exception and then check the resources to see if they've been correctly tidied up. That of course is testing for known situations, no matter what is a bit more difficult.
We too use a lot of streams, but basically we followed FxCop and best practice, wrote some utility routines and helper classes. After that it was religiously using using, or implementing IDisposable.
One other thing I'd thoroughly recomend is using the "full" version of FileStream for read and write to disk.
You don't see something like
Instead we do
Nail down as many unknowns as you can, if your chosen deity smiles upon you, it might all of them in a pragmatic and pratical sense.