你如何在 C# 中模拟文件系统进行单元测试? [英] How do you mock out the file system in C# for unit testing?

查看:29
本文介绍了你如何在 C# 中模拟文件系统进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何库或方法可以模拟 C# 中的文件系统来编写单元测试?在我目前的情况下,我有一些方法可以检查某个文件是否存在并读取创建日期.将来我可能需要更多.

Are there any libraries or methods to mock out the file system in C# to write unit tests? In my current case I have methods that check whether certain file exists and read the creation date. I may need more than that in future.

推荐答案

安装 NuGet 包 System.IO.Abstractions.

Install the NuGet package System.IO.Abstractions.

最初接受此答案时,此包不存在.原始答案是针对以下历史背景提供的:

This package did not exist when this answer was originally accepted. The original answer is provided for historical context below:

你可以通过创建一个接口来实现:

You could do it by creating an interface:

interface IFileSystem {
    bool FileExists(string fileName);
    DateTime GetCreationDate(string fileName);
}

并创建一个真实"的实现,它使用System.IO.File.Exists() 等.然后您可以使用模拟框架;我推荐 Moq.

and creating a 'real' implementation which uses System.IO.File.Exists() etc. You can then mock this interface using a mocking framework; I recommend Moq.

有人完成了这项工作,并将其发布在网上这里.

somebody's done this and kindly posted it online here.

我使用这种方法在 IClock 中模拟了 DateTime.UtcNow接口(对于我们的测试真的非常有用,能够控制时间的流动!),更传统的是,一个 ISqlDataAccess界面.

I've used this approach to mock out DateTime.UtcNow in an IClock interface (really really useful for our testing to be able to control the flow of time!), and more traditionally, an ISqlDataAccess interface.

另一种方法可能是使用 TypeMock,这允许您拦截对类的调用并将它们存根.然而,这确实需要花费钱,并且需要安装在您整个团队的 PC 上,并且您的构建服务器为了运行,而且,它显然不适用于System.IO.File,因为它不能存根 mscorlib.

Another approach might be to use TypeMock, this allows you to intercept calls to classes and stub them out. This does however cost money, and would need to be installed on your whole team's PCs and your build server in order to run, also, it apparently won't work for the System.IO.File, as it can't stub mscorlib.

您也可以接受某些方法不可单元测试并在单独的缓慢运行的集成/系统测试中测试它们套房.

You could also just accept that certain methods are not unit testable and test them in a separate slow-running integration/system tests suite.

这篇关于你如何在 C# 中模拟文件系统进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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