单元/集成测试中文件系统依赖的最佳实践 [英] Best practices for file system dependencies in unit/integration tests

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

问题描述

我刚开始为大量代码编写测试.有一堆类依赖于文件系统,即它们读取 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.

目前测试文件存储在项目的 test 目录中(它是一个 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,这些 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.

您可以模拟文件系统/数据库/网络访问你的单元测试.

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天全站免登陆