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