Does the module test a function that is output through XmlWriter?

I'm trying to get into unit testing and the TDD way to do something, but I ran into a problem, I'm not sure what to do with it.

I have a collection that saves itself to disk using XDocument and XmlWriter. I know that you should not write the file to disk, and then check it so that I get the output of XmlWriter in the memory stream, and then check the contents of the memory stream. The function is as follows:

public void Save() { using (XmlWriter xmlWriter = XmlWriter.Create(m_StreamProvider.SaveFileStream(m_FilenameProvider.Filename))) { XDocument xDoc = new XDocument(new XElement("BookmarkCollection", Items.Select(bookmark => new XElement("Bookmark", new XElement("Name", bookmark.Name), new XElement("Link", bookmark.Link), new XElement("Remarks", bookmark.Remarks), new XElement("DateAdded", bookmark.DateAdded), new XElement("DateLastAccessed", bookmark.DateLastAccessed)) ) )); xDoc.Save(xmlWriter); } } 

And unit test is

 [Test] public void Save_OneItemCollection_XmlCreatedCorrectly() { //Arrange MemoryStreamProvider streamProvider = new MemoryStreamProvider(); IBookmarkCollection collection = XBookmarkTestHelpers.GetXBookmarkCollection(streamProvider); IBookmark bookmarkToAdd = XBookmarkTestHelpers.GetIBookmark("myLink"); collection.Add(bookmarkToAdd); //Act collection.Save(); //Assert streamProvider.WriteStrean.Position = 0; String generatedXml = Encoding.Default.GetString(streamProvider.WriteStrean.GetBuffer()); Assert.IsTrue(String.Equals(generatedXml, m_ExpectedOneItemString), "XML does not match"); } 

The statement here is not too fragile (I know I can use String.Compare (), but it would have similar problems.) Am I testing correctly? Am I mocking what happened?

The whole entrance is much appreciated!

+4
source share
2 answers

The first thing that seems wrong in the Save function is that it actually has two responsibilities: it selects the storage and serializes the object graph for this storage. I would start by highlighting responsibility:

 public void Save(XmlWriter xmlWriter) { XDocument xDoc = new XDocument(new XElement("BookmarkCollection", Items.Select(bookmark => new XElement("Bookmark", new XElement("Name", bookmark.Name), new XElement("Link", bookmark.Link), new XElement("Remarks", bookmark.Remarks), new XElement("DateAdded", bookmark.DateAdded), new XElement("DateLastAccessed", bookmark.DateLastAccessed)) ) )); xDoc.Save(xmlWriter); } public void Save() { using (XmlWriter xmlWriter = XmlWriter.Create(m_StreamProvider.SaveFileStream(m_FilenameProvider.Filename))) { Save(xmlWriter); } } 

As for unit test, you can define an XSD schema and then validate the XML result for that schema, and also verify that it contains the values ​​you are looking for.

+4
source

In such cases, I use XNode.DeepEquals to compare XML instances with each other, since it compares the structure, not the bytes.

0
source

All Articles