你如何模拟出的单元测试在C#中的文件系统? [英] How do you mock out the file system in C# for unit testing?

查看:107
本文介绍了你如何模拟出的单元测试在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.

推荐答案

您可以通过创建一个接口做到这一点:

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.

我用这个方法来模拟出DateTime.UtcNow在IClock接口(真的真的有用我们的测试,以能控制时间的流动!),更传统,一个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 ,这使您可以来电拦截类和存根出来。但这不过费钱,而且需要才能运行,同时,它显然不会为有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#中的文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆