测试读写文件系统的类时的单元测试最佳实践 [英] Unit test best practice when testing class that reads and writes to the filesystem

查看:91
本文介绍了测试读写文件系统的类时的单元测试最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类对磁盘上的文件进行操作。
更确切地说,它遍历一个目录,读取具有给定后缀
的所有文件,并对数据执行一些操作,然后将它们输出到新文件。

I have a class that does operations on file's on a disk. More exactly it traverses a directory, reads through all files with a given suffix and does some operations on the data and then outputs them to a new file.

我对如何为这门课程设计单元测试有点怀疑。
我在想安装方法在/ tmp / somefolder中创建临时目录和临时文件,但我怀疑这是一个坏主意,原因有两个(开发人员使用Windows,文件权限等)。

I'm a bit dubious as to how to design a unittest for this class. I'm thinking having the setup method create a temporary directory and temporary files in /tmp/somefolder, but I'm suspecting this is a bad idea for a couple of reasons(Developers using windows, file permissions etc).

另一个想法是模拟我用来编写和读取磁盘的类,通过使用接口封装类然后提供模拟对象,但是它看起来有点乱。

Another idea would be to mock the classes I'm using to write and read to the disk, by encapsulating the classes using an interface and then providing a mock object, but it seems to be a bit messy.

接近这个问题的标准方法是什么?

What would be the standard way of approaching such a problem?

推荐答案

你的策略是正确的,IMO。请确保不要对临时目录进行硬编码。使用 System.getProperty(java.io.tmpdir)获取临时目录的路径,并在测试中使用finally块或 @After 测试完成后清理创建的文件和目录的方法。

Your strategy is the right one, IMO. Just make sure not to hardcode the temp directory. Use System.getProperty("java.io.tmpdir") to get the path of the temp directory, and use a finally block in your test or a @After method to cleanup the created files and directories once your test is finished.

这篇关于测试读写文件系统的类时的单元测试最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆