• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

您在 C# 模拟文件系统以进行单元测试?

用户头像
it1352
帮助5

问题说明

是否有任何库或方法可以在 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.

正确答案

#1

安装 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
系列文章
更多 icon
同类精品
更多 icon
继续加载