How can the FileInfo class be mocked using System.IO.Abstractions?

Viewed 52

I have injected the System.IO.Abstractions.IFileSystem interface into a class so that I can unit test file system interactions. There is one place in the class that uses new FileInfo(fileName). What is the replacement for that when using the IFileSystem interface and MockFileSystem?

Replacing File.OpenRead with _fileSystem.File.OpenRead is simple...

public string? Decrypt(string encryptedFilePath, string privateKeyArmor, string passPhrase)
    {
        try
        {
            using var privateKeyStream = new MemoryStream(Encoding.ASCII.GetBytes(privateKeyArmor));
            using var encryptedFileStream = _fileSystem.File.OpenRead(encryptedFilePath);

            var inputStream = PgpUtilities.GetDecoderStream(encryptedFileStream);
...

...but I don't know how to replace new FileInfo(fileName) here.

private byte[] CompressFile(string fileName, CompressionAlgorithmTag algorithm)
    {
        var outputStream = new MemoryStream();
        var compressedDataGen = new PgpCompressedDataGenerator(algorithm);
        PgpUtilities.WriteFileToLiteralData(compressedDataGen.Open(outputStream), PgpLiteralData.Binary,
            new FileInfo(fileName));
...

I tried _fileSystem.FileInfo.FromFileName(fileName), but that returns IFileInfo instead of FileInfo and the WriteFileToLiteralData method won't take that.

0 Answers
Related