How do you mock out the file system in C# for unit testing?(您如何在 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() 等.然后您可以使用模拟框架;我推荐 起订量.
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# 中模拟文件系统以进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:您如何在 C# 中模拟文件系统以进行单元测试?
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01