单元/集成测试中文件系统相关性的最佳做法 [英] Best practices for file system dependencies in unit/integration tests

查看:151
本文介绍了单元/集成测试中文件系统相关性的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始为很多代码编写测试。有一堆依赖于文件系统的类,即它们读取CSV文件,读/写配置文件等。

I just started writing tests for a lot of code. There's a bunch of classes with dependencies to the file system, that is they read CSV files, read/write configuration files and so on.

目前,测试文件存储在项目的测试目录(它是一个Maven2项目),但由于几个原因,该目录并不总是存在,所以测试失败。

Currently the test files are stored in the test directory of the project (it's a Maven2 project) but for several reasons this directory doesn't always exist, so the tests fail.

你知道最佳做法在单元/集成测试中处理文件系统依赖关系?

Do you know best practices for coping with file system dependencies in unit/integration tests?

编辑:我没有在上面描述的具体问题找到答案。这只是一个例子。我喜欢一般的建议如何处理文件系统/数据库等的依赖。

I'm not searching an answer for that specific problem I described above. That was just an example. I'd prefer general recommendations how to handle dependencies to the file system/databases etc.

推荐答案

首先应该尝试将单元测试远离文件系统 - 请参阅此设置单位测试规则。如果可能的话,您的代码将使用Streams(即在内存中)进行单元测试,并在生产代码中使用FileStream。

First one should try to keep the unit tests away from the filesystem - see this Set of Unit Testing Rules. If possible have your code working with Streams that will be buffers (i.e. in memory) for the unit tests, and FileStream in the production code.

如果这不可行,您可以让您的单元测试生成所需的文件。这使得测试易于阅读,因为所有内容都在一个文件中。这可能也会阻止权限问题。

If this is not feasible, you can have your unit tests generates the files they need. This makes the test easy to read as everything is in one file. This may also prevent permissions problem.

您可以 mock 单元测试中的文件系统/数据库/网络访问。

You can mock the filesystem/database/network access in your unit tests.

您可以将依靠数据库或文件系统的单元测试考虑为集成测试。

You can consider the unit tests that rely on DB or file systems as integration tests.

这篇关于单元/集成测试中文件系统相关性的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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