Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock File methods in .NET (like File.Copy("1.txt", "2.txt"))

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.

like image 981
Jim Avatar asked Nov 05 '08 21:11

Jim


People also ask

How do you mock a file system?

One option is to create a fake object that emulates the file system with an in-memory representation of it. The other possibility is to set up a test spy/mock for each test method. Considering the initial code snippet, both approaches are inappropriate. Let's see how dependency injection can help us.

How do you mock a method in C#?

Trying to mock a method that is called within another method. // code part public virtual bool hello(string name, int age) { string lastName = GetLastName(); } public virtual string GetLastName() { return "xxx"; } // unit test part Mock<Program> p = new Mock<Program>(); p. Setup(x => x. GetLastName()).

What is a mock file?

Mocking means creating a fake version of an external or internal service that can stand in for the real one, helping your tests run more quickly and more reliably. When your implementation interacts with an object's properties, rather than its function or behavior, a mock can be used.

What is mock test in .NET core?

A mock version of something is an object that can act like the real thing but can be controlled in test code. Moq (pronounced “mok u” or “mock”) is a library available on NuGet that allows mock objects to be created in test code and it also supports . NET Core.


2 Answers

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!!!
}
like image 67
yfeldblum Avatar answered Oct 03 '22 18:10

yfeldblum


If you absolutely have to do this, Typemock Isolator is your friend.

I can't say I've used it myself, and I would try to design my way around it instead, but it'll do the job as far as I'm aware.

like image 37
Jon Skeet Avatar answered Oct 03 '22 19:10

Jon Skeet