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

标签 c# unit-testing mocking

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

最佳答案

编辑:安装 NuGet 包 System.IO.Abstractions .

最初接受此答案时,此包不存在。为以下历史背景提供了原始答案:

You could do it by creating an interface:

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

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.

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

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.

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# 中模拟文件系统以进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1087351/

相关文章:

c# - 最小起订量 - 安装方法中的 LINQ 谓词

Python补丁: calling nested method in class doesn't work

java - 如何设计可用于模拟的私有(private)/ final方法?

c# - C# 是否具有与 Objective-c 的类别等效的功能?

c# - Orderby 不调用提供的比较器的 Compare()

c# - 在 Visual Studio 解决方案中组织共享库的单元测试项目

java - 使用 Maven 运行单个测试方法

unit-testing - 单元测试(模拟)数据库,如何使用模拟验证数据库方法?

c# - Excel自动化 : Range. 查找

c# - 使用泛型访问基抽象类方法中的子类对象