Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock the FileInfo information for a file?

I have a scenario in which I need much of the information from the FileInfo structure -- creation time, last write time, file size, etc. I need to be able to get this information cleanly, but also be able to truly unit test without hitting the file system.

I am using System.IO.Abstractions, so that gets me 99% of the way there for most of my class, except this one. I don't know how to use it to get the information I need from my MockFileSystem object.

public void Initialize(IFileSystem fs, string fullyQualifiedFileName)
{
    string pathOnly = fs.Path.GetDirectoryName(fullyQualifiedFileName);
    string fileName = fs.Path.GetFileName(fullyQualifiedFileName);

    // Here's what I don't know how to separate out and mock
    FileInfo fi = new FileInfo(fullyQualifiedFileName);

    long size = fi.LongLength;
    DateTime lastWrite = fi.LastWriteTime;
    ...
    ...
}

Any help on that line would be greatly appreciated.

UPDATE:

This is not an exact duplicate of existing questions because I'm asking how do I do it with System.IO.Abstractions, not how do I do it in general.

For those who are interested, I did find a way to accomplish it:

FileInfoBase fi = fs.FileInfo.FromFileName(fullFilePath);

If I use this line, I get the same information I need in both TEST and PROD environments.

like image 947
Jerry Avatar asked May 17 '17 16:05

Jerry


1 Answers

https://github.com/TestableIO/System.IO.Abstractions/blob/5f7ae53a22dffcff2b5716052e15ff2f155000fc/src/System.IO.Abstractions/IFileInfo.cs

System.IO.Abstractions provides you with an IFileInfo interface to code against, which you could create your own implementation of to return the stats you're interested in testing against.

In this case you'd want another method to return an IFileInfo to your Initialize method, which could be virtual so that in your test it just returns your fake instead of really hitting the system.

like image 146
Jason Bray Avatar answered Dec 13 '22 02:12

Jason Bray