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.
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.
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()).
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.
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.
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!!!
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With