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

Jim*_*Jim 14 .net unit-testing mocking

我们有一些调用File.Copy,File.Delete,File.Exists等的方法.如何在不实际访问文件系统的情况下测试这些方法?

我认为自己是一个单元测试n00b,所以任何建议都表示赞赏.

yfe*_*lum 23

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!!!
}
Run Code Online (Sandbox Code Playgroud)