5

I have the below TestMethod I am testing with VS 2013 and I am using 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);            
}

For the above TestMethod If i have to use Stub, how should it be modfied and will that be a good practice to use the stub instead of XMLDocument ?

I have tried this but not sure if this is suffice or not.

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);  
Fjodr
  • 919
  • 13
  • 32
krrishna
  • 2,050
  • 4
  • 47
  • 101
  • It seems that your class under test(CMATracer) use XmlAttributeCollection so you were mocked the wrong thing. please add the C'tor implementation of CMATracer. – Old Fox May 23 '15 at 17:46

1 Answers1

0

I imagine it's possible to use Microsoft Fakes to stub the XmlDocument, but stubbing will end up resulting in a very brittle test that breaks whenever you change the method calls used in the underlying implementation.

My suggestion would be to check the before and after states for your xml. This way no matter what changes in your CMATracer code, your tests will still pass.

    [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);
    }
s3raph86
  • 556
  • 4
  • 17