具有文件系统依赖性的单元测试代码 [英] Unit testing code with a file system dependency

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

问题描述

我正在编写一个组件,给定一个ZIP文件,需要:

I am writing a component that, given a ZIP file, needs to:


  1. 解压缩文件。

  2. 在解压缩的文件中查找特定的DLL。

  3. 通过反射加载该DLL,并调用该方法。

我想单元测试这个组件。

I'd like to unit test this component.

我很想写代码直接处理文件系统:

I'm tempted to write code that deals directly with the file system:

void DoIt()
{
   Zip.Unzip(theZipFile, "C:\\foo\\Unzipped");
   System.IO.File myDll = File.Open("C:\\foo\\Unzipped\\SuperSecret.bar");
   myDll.InvokeSomeSpecialMethod();
}

但是人们经常会说:不要写依赖于文件系统,数据库,网络等。

But folks often say, "Don't write unit tests that rely on the file system, database, network, etc."

如果我以单元测试友好的方式写这个,我想这样会是这样的:

If I were to write this in a unit-test friendly way, I suppose it would look like this:

void DoIt(IZipper zipper, IFileSystem fileSystem, IDllRunner runner)
{
   string path = zipper.Unzip(theZipFile);
   IFakeFile file = fileSystem.Open(path);
   runner.Run(file);
}

Yay!现在是可测试的我可以进行测试双打(mocks)到DoIt方法。但是在什么成本?我现在不得不定义3个新的接口来做这个可测试。我正在测试什么?我正在测试我的DoIt功能与其依赖关系正确地进行交互。它不测试zip文件是否正确解压缩等。

Yay! Now it's testable; I can feed in test doubles (mocks) to the DoIt method. But at what cost? I've now had to define 3 new interfaces just to make this testable. And what, exactly, am I testing? I'm testing that my DoIt function properly interacts with its dependencies. It doesn't test that the zip file was unzipped properly, etc.

它不觉得我正在测试功能了。感觉就像我只是测试课堂互动。

It doesn't feel like I'm testing functionality anymore. It feels like I'm just testing class interactions.

我的问题是这个:单位测试依赖于什么的正确方法是什么文件系统?

My question is this: what's the proper way to unit test something that is dependent on the file system?

编辑我正在使用.NET,但这个概念也可以应用Java或本机代码。

edit I'm using .NET, but the concept could apply Java or native code too.

推荐答案

这真的没有什么问题,这只是一个问题,你是否称之为单元测试或集成测试。您只需确保如果您与文件系统进行交互,则没有意外的副作用。具体来说,请确保在您自己以后清理 - 删除您创建的任何临时文件,并且不会意外覆盖与您正在使用的临时文件具有相同文件名的现有文件。总是使用相对路径,而不是绝对路径。

There's really nothing wrong with this, it's just a question of whether you call it a unit test or an integration test. You just have to make sure that if you do interact with the file system, there are no unintended side effects. Specifically, make sure that you clean up after youself -- delete any temporary files you created -- and that you don't accidentally overwrite an existing file that happened to have the same filename as a temporary file you were using. Always use relative paths and not absolute paths.

chdir()变成一个好主意运行测试之前的临时目录,然后再次 chdir()

It would also be a good idea to chdir() into a temporary directory before running your test, and chdir() back afterwards.

这篇关于具有文件系统依赖性的单元测试代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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