需要:.NET中的文件系统接口和实现 [英] Needed: File system interfaces and implementation in .NET

查看:179
本文介绍了需要:.NET中的文件系统接口和实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

您如何嘲笑C#中的文件系统进行单元测试?

我将单元测试写入我的代码,使用Moq作为嘲笑框架。

我的代码包括调用文件系统,使用直接调用 System.IO 类。例如, File.Exists(...)

我想将该代码更改为更可测试,所以我应该一个界面,说 IFile ,使用相关方法,说存在(字符串路径)

我知道我可以从头开始编写它,但我认为可能有一个完整的,强大的框架,它具有文件系统的接口和实现。这个(所需的)框架也可能是某种服务,因此它的API不一定是与 System.IO 命名空间的接口等效 。

请注意,我真的希望有接口(而且不是静态方法),以便我的代码准备好依赖注入

I write unit tests to my code, using Moq as a mocking framework.
My code includes calls to the file system, using direct calls to System.IO classes. For instance, File.Exists(...) etc.
I'd like to change that code to be more testable, so I should have an interface, say IFile, with a relevant method, say Exists(string path).
I know I can write it from scratch, but I thought that maybe there's a complete, robust framework that has both interfaces and implementations for the file system. This (desired) framework may also be some kind of a "service", and therefore its API doesn't have to be an "interface equivalent" to the System.IO namespace.
Note that I'd really like to have interfaces (and not static methods) so that my code is ready for dependency injection


  • 某种方式类似,但不一样的问题在stackoverflow
  • 中要求
  • codeplex.com 中有一个名为CodePlex Source Control Client的项目(链接)在源代码中有这样的类(参见 / Source / TfsLibrary / Utility / code>在源代码中的具体细节)

  • A somehow similar, yet not the same question was asked in stackoverflow
  • In codeplex.com there's a project named CodePlex Source Control Client (link) that has such classes in the source code (see /Source/TfsLibrary/Utility/ in the source code for specific details)

任何其他建议?

推荐答案

我对于静态 System.IO.File 目录方法的已写入适配器。然后在我的课程中,我执行以下操作:

I've written adapters for the static System.IO.File and Directory methods. Then in my classes I do the following:

public class MyService {
  public IFile File {private get;set;}
  public MyService() {
    File = new FileImpl();
  }
  public void DoSomething() {
    File.ReadAllText("somefile");
  }
}

然后,您可以将模拟注入为IFile进行测试。

Then you can inject a mock as IFile for testing.

这篇关于需要:.NET中的文件系统接口和实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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