How do I mock the FileInfo information for a file?
Asked Answered
U

2

14

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.

Unbelt answered 17/5, 2017 at 16:2 Comment(3)
SystemWrapper NuGetBemoan
"I'm asking how do I do it with System.IO.Abstractions" - your question didn't mention that as a restriction, I've retracted my close vote. So adding a library such as SystemWrapper mentioned by @Bemoan also isn't an option? Anyway, feel free to post a self-answer.Mord
What is the edition of visual studio that you use? if it is enterprise you can use Microsoft Fakes to accomplish this.Tombolo
B
1

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.

Bootstrap answered 11/10, 2022 at 20:10 Comment(0)
D
0

The intended way is now to use this abstraction IFileSystem.FileInfo.New (and no longer FileInfo.FromFileName, which is now deprecrated), like this:

var fi = fs.FileInfo.New(fullFilePath);

Danu answered 26/2 at 8:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.