如何对创建和读取文件的方法进行单元测试
我实现了两个静态 void
方法来创建文件和读取文件。 我想测试这些方法,但我不知道如何测试与文件一起使用的方法。 最好的方法是什么?
我正在使用 Java 和 JUnit。
I have implemented two static void
methods which create files and read files.
And I want to test the methods but I don't know how to test methods which work with files.
What is the best way to do that?
I'm using Java and JUnit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的方法是重构您的方法以使用输入/输出流而不是直接使用文件。通过这种方式,您可以在单元测试中轻松地将 StringReaders/Writers 传递给它们(前提是它们使用文本文件 - 如果不是,您需要适当类型的流)。
如果您直接使用文件,您的单元测试会变得更加复杂,因为它们需要额外的设置/拆卸代码来创建和清理测试目录,以及每个测试中的读/写文件,这会减慢测试速度。此外,它还可能出现一些问题,例如无权在特定目录中写入(例如,因为它是在另一个开发人员启动的测试运行中创建的)、磁盘已满错误等。最好让您的单元测试自行进行- 尽可能多地包含。
The best would be to refactor your methods to work with input/output streams rather than with files directly. This way you can easily pass StringReaders/Writers to them in unit tests (provided they work with text files - if not, you need the appropriate kind of streams).
If you work directly with files, your unit tests become more complicated, as they need extra setup/teardown code to create and clean up the test directory, plus read/write files in each test, which slows the tests down. Also, it opens up the possibility to problems such as having no right to write in a specific directory (e.g. because it was created in a test run started by another developer), disk full error etc. It is better to keep your unit tests self-contained as much as possible.
您可以创建一个 test/resources 目录,其中包含专门用于测试的文件。这样做的缺点是您的代码需要能够传入路径,即使代码现在不是这样设计的,这也不应该成为太大的障碍。
因此,在您的测试中,您需要
记住一件事,那就是,如果您使用绝对路径,不同的开发人员可能有不同的资源路径,因此您可能需要使用配置文件...
you can create a test/resources directory with files in it specifically for testing. The downside of this is that your code needs to be able to have the path passed in, which shouldn't be too much a hurdle even it the code isn't designed that way now.
so in your test you would have something like
one thing to keep in mind is that if you use absolute paths different developers might have different paths to the resources, so you might need to use configuration files...