单元测试通过XmlWriter输出的函数?

时间:2009-10-08 18:58:35

标签: c# .net unit-testing

我正在尝试进行单元测试和TDD做事方式,但我遇到了一个问题,我不知道该怎么办。

我有一个使用XDocument和XmlWriter将自己保存到磁盘的集合。我知道你不应该把文件写入磁盘然后检查它,所以我把XmlWriter输出到内存流然后我检查了内存流的内容。该函数如下所示:

   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);
        }

    }

单元测试是

[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");
    }

这里的断言太脆弱了(我知道我可以使用String.Compare()但它会有类似的问题。),我测试的是正确的吗?我嘲笑错了吗?

所有输入都非常感谢!

2 个答案:

答案 0 :(得分:4)

Save函数首先感觉错误的是它实际上有两个职责:它选择一个存储并将对象图序列化到这个存储。我首先要分离职责:

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);
    }
}

就单元测试而言,您可以定义XSD架构,然后根据此架构validate结果XML,并测试它是否包含您要查找的值。

答案 1 :(得分:0)

在这种情况下,我使用XNode.DeepEquals来比较XML实例,因为它比较结构,而不是字节。