在.NET中模拟文件的方法(如File.Copy(" 1.txt的"," 2.txt")) [英] Mock File methods in .NET (like File.Copy("1.txt", "2.txt"))

查看:150
本文介绍了在.NET中模拟文件的方法(如File.Copy(" 1.txt的"," 2.txt"))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个叫File.Copy,File.Delete,File.Exists等一些方法如何,我们可以测试这些方法没有实际碰到文件系统?

我认为我是一个单元测试的n00b,所以任何的建议是AP preciated。

解决方案

 公共接口的IFile {
    无效复制(源字符串,字符串DEST);
    无效删除(字符串FN);
    布尔存在(字符串FN);
}

公共类FileImpl:{的IFile
    公共虚拟无效复制(源字符串,字符串DEST){File.Copy(来源,DEST); }
    公共虚拟无效删除(字符串FN){File.Delete(FN); }
    公共虚拟BOOL存在(字符串FN){返回File.Exists(FN); }
}

[测试]
公共无效TestMySystemCalls(){
    var文件=新Moq.Mock<的IFile>();
    VAR OBJ =新ClassUnderTest(文件系统);
    filesystem.Expect(FS => fs.Exists(MyFile.txt的))。返回(真);
    obj.CheckIfFileExists(); //不打底层的文件系统!
}
 

We have some methods that call File.Copy, File.Delete, File.Exists, etc. How can we test these methods without actually hitting the file system?

I consider myself a unit testing n00b, so any advice is appreciated.

解决方案

public interface IFile {
    void Copy(string source, string dest);
    void Delete(string fn);
    bool Exists(string fn);
}

public class FileImpl : IFile {
    public virtual void Copy(string source, string dest) { File.Copy(source, dest); }
    public virtual void Delete(string fn) { File.Delete(fn); }
    public virtual bool Exists(string fn) { return File.Exists(fn); }
}

[Test]
public void TestMySystemCalls() {
    var filesystem = new Moq.Mock<IFile>();
    var obj = new ClassUnderTest(filesystem);
    filesystem.Expect(fs => fs.Exists("MyFile.txt")).Return(true);
    obj.CheckIfFileExists(); // doesn't hit the underlying filesystem!!!
}

这篇关于在.NET中模拟文件的方法(如File.Copy(&QUOT; 1.txt的&QUOT;,&QUOT; 2.txt&QUOT;))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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