Unit Testing System.IO

27 Nov 21 (1 min read)
public class FileSample
{
    public bool ProcessText(string fileName)
    {
        var exists = File.Exists(fileName);
        if (exists)
        {
            var text = File.ReadAllText(fileName);
            // do something with `text`
            return true;
        }

        Console.WriteLine($"{fileName} not found!");
        return false;
    }
}
public interface IFileWrapper
{
    bool Exists(string fileName);
    string ReadAllText(string fileName);
    // same for all other methods used in your code
}
public class DefaultFileWrapper : IFileWrapper
{
    public bool Exists(string fileName) => File.Exists(fileName);
    public string ReadAllText(string fileName) => File.ReadAllText(fileName);
}
public class WrapperNonsense
{
    private IFileWrapper _wrapper;

    public WrapperNonsense() : this(new DefaultFileWrapper())
    {
    }

    public WrapperNonsense(IFileWrapper wrapper)
    {
        _wrapper = wrapper ?? throw new ArgumentNullException(nameof(wrapper));
    }

    public bool ProcessText(string fileName)
    {
        var exists = _wrapper.Exists(fileName);
        if (exists)
        {
            var text = _wrapper.ReadAllText(fileName);
            // do something with `text`
            return true;
        }

        Console.WriteLine($"{fileName} not found!");
        return false;
    }
}
public class AbstractionSample
{
    private IFileSystem _fs;

    public AbstractionSample() : this(new FileSystem())
    {
    }

    public AbstractionSample(IFileSystem fs)
    {
        _fs = fs ?? throw new ArgumentNullException(nameof(fs));
    }

    public bool ProcessText(string fileName)
    {
        var exists = _fs.File.Exists(fileName);
        if (exists)
        {
            var text = _fs.File.ReadAllText(fileName);
            // do something with `text`
            return true;
        }

        Console.WriteLine($"{fileName} not found!");
        return false;
    }
}
< back