Unit test best practice when testing class that reads and writes to the filesystem

耗尽温柔 提交于 2019-12-21 03:52:08

问题


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.

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?


回答1:


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.




回答2:


If using JUnit 4.7 and up, you can use the @TemporaryFolder rule to transparently obtain a temporary folder which should automatically get cleared after each test.




回答3:


Mocking everything out is possible, but probably much more effort than it's worth. You can use the temporary directory supplied from Java System.getProperty("java.io.tmpdir") which you should be able to write to etc. no matter which system you're on. Stick to short file names and you'll be safe even if running on something ancient.



来源:https://stackoverflow.com/questions/7345403/unit-test-best-practice-when-testing-class-that-reads-and-writes-to-the-filesyst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!