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))
{
using (var reader = XmlReader.Create(webshopXmlFileStream))
{
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?
source
share