gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:32:39 25 4
gpt4 key购买 nike

是否有任何库或方法可以在 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 usesSystem.IO.File.Exists() etc. You can then mock this interface using amocking 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 IClockinterface (really really useful for our testing to be able to controlthe flow of time!), and more traditionally, an ISqlDataAccessinterface.

Another approach might be to use TypeMock, this allows you tointercept calls to classes and stub them out. This does however costmoney, and would need to be installed on your whole team's PCs andyour build server in order to run, also, it apparently won't work forthe System.IO.File, as it can't stub mscorlib.

You could also just accept that certain methods are not unit testableand test them in a separate slow-running integration/system testssuite.

关于c# - 您如何在 C# 中模拟文件系统以进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1087351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com