【问题标题】:How to Stub the XMLDocument in VS 2013 using Microsoft Fakes如何使用 Microsoft Fakes 在 VS 2013 中存根 XMLDocument
【发布时间】:2015-05-21 15:49:13
【问题描述】:

我有以下TestMethod 我正在使用 VS 2013 进行测试,并且我正在使用 Microsoft Fakes。

[TestMethod]        
public void ConstructorTestForCMAClass()
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<add name=\"console\" type=\"System.Diagnostics.DefaultTraceCMA\" value=\"Error\"/>");
    XmlAttributeCollection attrColl = doc.DocumentElement.Attributes;
        CMATracer cMATracer = new CMATracer(attrColl);            
}

对于上述TestMethod,如果我必须使用存根,应该如何修改它,使用存根代替XMLDocument会是一个好习惯吗?

我已经尝试过了,但不确定这是否足够。

StubXmlDocument stubXmlDocument = new StubXmlDocument();
stubXmlDocument.LoadXml("<add name=\"console\" type=\"System.Diagnostics.DefaultTraceCMA\" value=\"Error\"/>");
//create a stub attribute collection
XmlAttributeCollection attrCollection = stubXmlDocument.DocumentElement.Attributes;
CMATracer cMATracer = new CMATracer(attrColl);  

【问题讨论】:

  • 您的测试类(CMATracer)似乎使用了 XmlAttributeCollection,所以您被嘲笑错了。请添加 CMATracer 的 C'tor 实现。

标签: c# unit-testing mstest microsoft-fakes


【解决方案1】:

我想可以使用 Microsoft Fakes 来存根 XmlDocument,但存根最终会导致一个非常脆弱的测试,每当您更改底层实现中使用的方法调用时就会中断。

我的建议是检查 xml 的前后状态。这样,无论您的 CMATracer 代码发生什么变化,您的测试仍然可以通过。

    [TestMethod]
    public void ConstructorTestForCMAClass()
    {
        // Arrange
        string xmlDocPreState  = "<add name=\"console\" type=\"System.Diagnostics.DefaultTraceCMA\" value=\"Error\"/>";
        string xmlDocPostState = "Whatever...";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlDocPreState);
        XmlAttributeCollection attrColl = doc.DocumentElement.Attributes;

        // Act
        CMATracer cMATracer = new CMATracer(attrColl);

        // Assert
        Assert.AreEqual(xmlDocPostState, doc.OuterXml);
    }

【讨论】:

    猜你喜欢
    • 2013-09-26
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2013-09-07
    • 1970-01-01
    • 2015-10-19
    • 2015-09-21
    相关资源
    最近更新 更多