Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9118901
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T05:15:56+00:00 2026-06-17T05:15:56+00:00

I am using Autofac as the DI container in a project. Now i have

  • 0

I am using Autofac as the DI container in a project. Now i have started to create unit tests using Moq in it. As the code for business class is already written, so i would like to avoid making major changes in the Business classes. I am facing problem in mocking System.IO.XXX classes (like FileSystemWatcher, Directory, File, StreamReader, etc). Mostly because either they are static classes or they do not have any interfaces.

// This is what one of my business class looks like

internal class SpanFileReader : ISpanFileReader
{
// Some private variables
    private string _filePath;
    private readonly ISpanLogger _spanLogger;

#region Public Properties
    // Prorperties....
#endregion

#region Constructor

public SpanFileReader(string filePath)
{
    _filePath = filePath;
    _spanLogger = IocContainer.Instance.Container.Resolve<ISpanLogger>();
}

#endregion

#region Public Methods

public bool ReadSpanRecords(CancellationToken ct)
{
    try
    {
        if (!VerifySpanFile())
            return false;

        _spanFileLines = new List<string>();

        using (var streamReader = new StreamReader(_filePath))
        {
            while (!streamReader.EndOfStream)
            {
                // some logic
            }
        return true;
        }
    }

    catch (OperationCanceledException operationCanceledException)
    {
        _spanLogger.UpdateLog("some message");
        throw;
    } 
    catch (Exception ex)
    {
        _spanLogger.UpdateLog("some message);
        throw;
    }
}

public void MoveFileToErrorFolder(string spanFileName)
{
    var spanFilePath = AppConfiguration.SpanFolderPath + spanFileName;
    var errorFilePath = AppConfiguration.SpanErrorFolderPath + spanFileName;
    try
    {
        if (File.Exists(spanFilePath))
        {
            if (!File.Exists(errorFilePath))
            {
                _spanLogger.UpdateLog("some message");
                File.Move(spanFilePath, errorFilePath);
                _spanLogger.UpdateLog("some message");
            }
            else
            {
                File.Delete(spanFilePath);
                _spanLogger.UpdateLog("some message");
            }
        }
        else
        {
            _spanLogger.UpdateLog("some message");
        }
    }
    catch (Exception ex)
    {
        _spanLogger.UpdateLog("some message");
        throw ex;
    }
}
}

Now i would like to use the StreamReader() in such a way that i can resolve its instance via some interface(say IStreamReader) using Autofac. So that while writing unit test for SpanFileReader(), i can register IStreamReader’s Moq instace in the container and use it instead of the actual instance.
I would like to do something similar with the File() class as well, so that i can provide my own moq implementation, which gets called when the SUT (the SpanFileReader instace) is tested.
Can someone please suggest a proper way to go about these scenarios.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T05:15:58+00:00Added an answer on June 17, 2026 at 5:15 am

    You mention two problems:

    How to mock StreamReader?

    1. Create your IStreamReader interface by copying the methods from StreamReader.
    2. Create a wrapper class StreamReaderWrapper which implements IStreamReader.
    3. In the wrapper’s constructor, create a StreamReader.
    4. For each method, forward the calls to the wrapped object.

    e.g.

    interface IStreamReader
    {
        string ReadLine();
        // etc...
    }
    
    public class StreamReaderWrapper : IStreamReader
    {
        private StreamReader _streamReader;
    
        public StreamReaderWrapper(string path)
        {
            _streamReader = new StreamReader(path);
        }
    
        public string ReadLine()
        {
            return _streamReader.ReadLine();
        }
    }
    

    Now replace new StreamReader() in your code, using Autofac (or any factory/IoC container). When testing, return a Mock<IStreamReader>() instead:

    using (var streamReader =
        IocContainer.Instance.Container.Resolve<IStreamReaderWrapper>(_filePath))
    {
        // ...
    }
    

    How to mock File?

    Do the same as above, instead creating a IFile and FileWrapper class with no constructor / wrapped object.

    Instantiate an instance of this wrapper for use by the whole class, and use this instance whereever you would normally use File.

    E.g.

    interface IFile
    {
        bool Exists(string name);
        // etc...
    }
    
    public class FileWrapper : IFile
    {
        public bool Exists(string name)
        {
            return File.Exists(name);
        }
    }
    

    then (from your example):

    public SpanFileReader(string filePath)
    {
        // ...
        _fileWrapper = IocContainer.Instance.Container.Resolve<IFileWrapper>();
    }
    
    public void MoveFileToErrorFolder(string spanFileName)
    {
        // ...
        if (_fileWrapper.Exists(spanFilePath))
        {
           // ...
        }
    }
    

    I find this a very clean pattern once used to it, as all constructor/method signatures are preserved. Having tests which do not touch the file system and are easily mocked is a huge advantage, and much faster too.

    An important tip is to avoid adding any logic at all to the wrappers, otherwise they may need testing too (so you’d have to create a wrapper wrapper …)!

    Classes like File can also be accessed via an instance, so you might like to create separate interfaces to keep the instance and static methods wrapper separately (IFileStatics?).

    One further idea is to build up a library of various wrapped .Net classes for future use, or create the wrappers automatically with various .NET technologies (Castle Dynamic Proxy for example).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to have the unit tests not rely on calling container.Resolve<T>() for their
I am using Autofac as my IoC container. I have: IRepository<> , my repository
Using Autofac, I have the following scenario: public class MainClass { public delegate MainClass
I working on asp.net mvc3 project. I am using autofac for DI. I have
I'm using Castle DynamicProxy with Autofac. I have an object for which I've created
I have run into an issue while creating a data service and using Autofac
I have started to use Autofac following this tutorials: http://flexamusements.blogspot.com/2010/09/dependency-injection-part-3-making-our.html Simple class with no
I'm newly experimenting with the cryptography application block while using Autofac as the container.
We're currently following the DI model using Autofac as an IoC container. We've recently
I have a master project that's using a fairly standard source tree approach +

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.