Search code examples
c#unit-testingmicrosoft-fakes

How to shim XmlAttribute using Microsoft Fakes in VS 2013


I have the below code I am testing.

    public Loader(XmlAttributeCollection attributes)
    {

        if (attributes == (XmlAttributeCollection)null)
            throw new ArgumentNullException("attributes");
        foreach (XmlAttribute attribute in attributes)
        {
            if (attribute.Name.Equals("name", StringComparison.OrdinalIgnoreCase))
            {
                name = attribute.Value;
            }
            else if (attribute.Name.Equals("type", StringComparison.OrdinalIgnoreCase))
            {
                loaderType = attribute.Value;
            }
            else
            {
                loaderAttributes.Add(attribute.Name, attribute.Value);
            }
        }
    }

Is that possible to shim the attribute/attributecollection so that I can return whichever the attribute object I want to return ?

For example I want to return two xmlattribute objects one with attribute name of "name" and another one as "type" and also their respective values .

What I meant is something like below shim statement where instead of returning null , can I return an xmlattribute object with name and value ?

            ShimXmlAttributeCollection.AllInstances.ItemOfGetInt32 = (x, y) =>
            {
                return null;
            };

Here is the sample xml I have.

<add name=\"console\" type=\"DefaultTraceLoader\" value=\"Error\"/>

Solution

  • You could:

    var xml = new XmlDocument();
    xml.LoadXml("<add name=\"console\" type=\"DefaultTraceLoader\" value=\"Error\"/>");
    var enumerator = xml.DocumentElement.Attributes.GetEnumerator();
    

    BEFORE setting the ShimXmlNamedNodeMap.AllInstances.GetEnumerator.

    ShimXmlNamedNodeMap.AllInstances.GetEnumerator = x =>
    {
        return enumerator;
    };