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

How do you mock out the file system in C# for unit testing?(您如何在 C# 中模拟文件系统以进行单元测试?)
本文介绍了您如何在 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# 中模拟文件系统以进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)