How to unit test(Rhino Mocks) file System without creating physical file ?

138 views
Skip to first unread message

A K Das

unread,
Oct 23, 2015, 5:52:53 AM10/23/15
to Rhino.Mocks
Dear All, 


Please help me on below issue.

We  have FileWriter Class below having constructor with mentioned parameter (string path, string name, string extension):-

    public class FileWriter
    {
        #region Global Declaration

        protected string filePath;
        protected string fileName;
        protected StreamWriter writer;
        protected FileInfo fileInfo;
        protected FileStream fileStream;

        protected const string newLineSyntax = "\r\n";
        protected const int MaxCommentLength = 2000;

        #endregion

        public FileWriter(string path, string name, string extension)
        {
            filePath = path;
            fileName = name;
            fileInfo = new FileInfo(filePath + "\\" + fileName + "." + extension);
            fileStream = fileInfo.Create();
            writer = new StreamWriter(fileStream);
            writer.AutoFlush = true;
        }
}

How to unit test ( public FileWriter(string path, string name, string extension)
) using Rhino Mocks without creating physical file  ?


Kind Regards ,

A K Das.

Patrick Steele

unread,
Oct 23, 2015, 8:33:49 AM10/23/15
to rhino...@googlegroups.com
Ideally, your constructors should not do much work.  From https://msdn.microsoft.com/en-us/library/ms229060(v=vs.110).aspx:

"Constructors should not do much work other than capture the constructor parameters. The cost of any other processing should be delayed until required."

If you re-factor your constructor to just capture the parameters and then make the file creation a standalone, virtual method.  You can use Rhino.Mocks to mock out the call to the virtual method to test the FileWriter class.

Another option would be to replace your direct filesystem access with an abstraction layer like https://github.com/tathamoddie/System.IO.Abstractions.

--
You received this message because you are subscribed to the Google Groups "Rhino.Mocks" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rhinomocks+...@googlegroups.com.
To post to this group, send email to rhino...@googlegroups.com.
Visit this group at http://groups.google.com/group/rhinomocks.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages