在.NET中模拟文件的方法(如File.Copy(" 1.txt的"," 2.txt"))文件、方法、File、NET

2023-09-03 10:57:26 作者:风起人散

我们有一个叫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(); //不打底层的文件系统!
}
 

vb.net 如何复制一个正在使用的文件

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!!!
}