How to unit test FileStream File.Open

First of all, I am familiar with the Mocking concept for Unit Tests, and I am writing an application in accordance with TDD.

I have a method in which I need to read a file. The file is read in:

 using (var webshopXmlFileStream = StreamFactory.Create(importFile))
 {
     // Opens a reader that will read the Xml file.
     using (var reader = XmlReader.Create(webshopXmlFileStream))
     {
         // Read the nodes "Node" and "ArticleGroup" recursively.
         var nodes = XmlReaderUtils.EnumerateAxis(reader, new[] { "Node", "ArticleGroup" });
     }
 }

Of course, this is not unit test -able.

So, I created an interface called IStreamFactorythat has one single method:

Stream Create(string filePath);

The implementation of this interface looks like this:

public Stream Create(string filePath)
{ 
  return File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None); 
}

So now I can make fun of the interface to return MemoryStream, for example:

const string webshopXmlData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                "<Node>" +
                                  "<Name></Name>" +
                                "</Node>";
var streamFactoryMock = new Mock<IStreamFactory>();
streamFactoryMock.Setup(action => action.Create(It.IsAny<string>())).Returns((string input) => new MemoryStream(Encoding.ASCII.GetBytes(webshopXmlData)));

The problem is that I'm testing module readeris nulland no nodesreturns to the application.

Does anyone have an idea about what happened?

+4
source share
1 answer

, , :

  • .

  • XmlDocument.

, , , , . , , . unit test , xml node:

class
{   

    void LoadNodes(IFileLoader loader)
    {
         using(var reader = loader.GetReader()) 
         {
              var nodes = XmlReaderUtils.EnumerateAxis(reader, new[] { "Node", "ArticleGroup" });
         }

    }
}
+6

All Articles