您在 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.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanghfiee
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20