Search code examples
c#unit-testingxmlunit

DiffBuilder - ignore element value but make sure the XML node is present


I am using DiffBuilder to compare two XML files. For the given element Product, I want to check that the element is present but I want to ignore its value. Is it possible using XmlUnit ?

My code below will work regardless of the presence of the Product element, which doesn't work for what I need

var differenceBuilder = DiffBuilder
                .Compare(Input.FromDocument(controlXmlFile))
                .WithTest(Input.FromDocument(testXmlDile))
                .WithNodeFilter(n => n.Name != "Product");

Solution

  • In this case you don't want to throw away the node itself but the differences between the nodes. You wouldn't use a NodeFilter but rather a DifferenceEvaluator for this.

    A very simplified version could be something like

    .WithDifferenceEvaluator((comparison, outcome) =>
            comparison.ControlDetails.Target.Name == "Product" ? ComparisonResult.EQUAL : outcome
        ) 
    

    but you'd need to take into account that ControlDetails could be null (and look at TestDetails instead) for example. And if your Product node has child elements you may want to either filter them out with NodeFilter or check whether any parent of the current comparison target is named Product.