问题描述
可能重复:
你如何模拟在 C# 中取出文件系统进行单元测试?
我为我的代码编写单元测试,使用 Moq 作为模拟框架.
我的代码包括对文件系统的调用,使用对 System.IO
类的直接调用.例如 File.Exists(...)
等
我想将该代码更改为更具可测试性,因此我应该有一个接口,例如 IFile
,并带有相关方法,例如 Exists(string path)
.
我知道我可以从头开始编写它,但我认为也许有一个完整、健壮的框架,它同时具有文件系统的接口和实现.这个(期望的)框架也可以是某种服务",因此它的API不必是接口等价物".到 System.IO
命名空间.
请注意,我真的很想拥有接口(和 not 静态方法),以便我的代码可以进行依赖注入
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 的项目(<在源代码中有此类类的 href="http://codeplexclient.codeplex.com/" rel="noreferrer">link)(参见
/Source/TfsLibrary/Utility/
具体详见源代码)
- 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
和 Directory
方法编写了适配器.然后在我的课程中,我执行以下操作:
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");
}
}
然后你可以注入一个 mock 作为 IFile 进行测试.
Then you can inject a mock as IFile for testing.
这篇关于需要:.NET 中的文件系统接口和实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!