Dir*_*gen 7 .net c# unit-testing moq
可能重复:
.NET文件系统包装程序库
我想写一个测试文件内容加载的测试.在示例中,用于加载内容的类是
FileClass
Run Code Online (Sandbox Code Playgroud)
和方法
GetContentFromFile(string path).
Run Code Online (Sandbox Code Playgroud)
有没有办法嘲笑
File.exists(string path)
Run Code Online (Sandbox Code Playgroud)
使用moq的给定示例中的方法?
例:
我有一个类有这样的方法:
public class FileClass
{
public string GetContentFromFile(string path)
{
if (File.exists(path))
{
//Do some more logic in here...
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于Exists方法是File类的静态方法,因此无法模拟它(请参阅底部的注释).解决此问题的最简单方法是在File类周围编写一个瘦包装器.这个类应该实现一个可以注入到类中的接口.
public interface IFileWrapper {
bool Exists(string path);
}
public class FileWrapper : IFileWrapper {
public bool Exists(string path) {
return File.Exists(path);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的班上:
public class FileClass {
private readonly IFileWrapper wrapper;
public FileClass(IFileWrapper wrapper) {
this.wrapper = wrapper;
}
public string GetContentFromFile(string path){
if (wrapper.Exists(path)) {
//Do some more logic in here...
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意: TypeMock允许您模拟静态方法.其他流行的框架,例如Moq,Rhino Mocks等,则不然.
| 归档时间: |
|
| 查看次数: |
8859 次 |
| 最近记录: |