How can I write unit tests using Moq for DirectoryInfo
? My class is as below:
public class DataProcessor : IDataProcessor, IDisposable
{
private ILogger _logger;
DataProcessor(ILogger logger)
{
_logger = logger;
}
public async Task Run(string filePath)
{
var dir = new DirectoryInfo( filePath);
var filesInDir = dir.GetFiles("*.xml");
foreach(var filePath in filesInDir)
{
// process file
}
}
}
I tried using System.IO.Abstractions and changed my class as below but DirectoryInfo
does not work with System.IO.Abstractions
public class DataProcessor : IDataProcessor, IDisposable
{
private readonly IFileSystem _fileSystem;
private ILogger _logger;
DataProcessor(ILogger logger) : this(new FileSystem())
{
_logger = logger;
}
internal DataProcessor(IFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
public async Task Run(string filePath)
{
var dir = new _fileSystem.DirectoryInfo(filePath);// ERROR HERE
var filesInDir = dir.GetFiles("*.xml");
foreach(var filePath in filesInDir)
{
// process file
}
}
}
The error I get is
The name or namespace name '_fileSystem' does not exist.
Is this because I am not doing it right or this can't be done?
var dir = new _fileSystem.DirectoryInfo( filePath);
to do? Thenew
operator expects a type to follow (class Xyz {}
and thenvar xyz = new Xyz();
). You are passing it whatever_fileSystem.DirectoryInfo
returns.IFileSystem.EnumerateFiles
instead ofnew DirectoryInfo( filePath)