Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an attribute from testing in XMLUnit in Java?

I wanted to skip two attributes from my acceptance test.So I added following part to remove that two attributes.This is given me a error: junit.framework.AssertionFailedError: org.custommonkey.xmlunit.Diff [different] Expected number of element attributes '2' but was '1'

Part of XML file:

<a:content schemaVS="1"
a:schemaLocate="http://www.ContentXML.xsd"
whiteSpaceMode="preserve">
<section type="Chapter" id="drd121">
    <p type="H1">This is H1.</p>
</section>

Part of Java implementation:

public Document removeIgnoredCxmlNodes(Document resultDocument) {

Element contentElement=(Element) resultDocument.getElementsByTagName("a:content").item(0);
contentElement.removeAttribute("schemaVS");
contentElement.removeAttribute("a:schemaLocate");
return resultDocument;

}

public void cxmlShouldBeProduced(String location) throws Throwable {
try {
    Document expectedDocument = parseDocument(RESOURCES_DIR_PATH.resolve(location));
    Document resultDocument = removeIgnoredCxmlNodes(parseDocument(resultCxmlPath));
    assertXMLEqual(expectedDocument, resultDocument);
    } catch (NullPointerException e) {
        e.printStackTrace();
    }

}

like image 329
user2490093 Avatar asked Mar 20 '26 02:03

user2490093


2 Answers

This is a result of using the default implementation of DifferenceListener. To specify that a comparison should ignore a particular type of difference, you need to provide your own implementation.

The following example is for XMLUnit 1. I haven't yet used 2, but from what I understand the solution would be much the same.

public class DifferenceListenerImpl implements DifferenceListener {
  @Override
  public int differenceFound(Difference d) {
    if (d.getId() == DifferenceConstants.ELEMENT_NUM_ATTRIBUTES_ID) {
      return RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR;
    }
    // handle other difference types here
  }

  @Override
  public void skippedComparison(Node control, Node test) {
    // not needed
  }
}
like image 64
jsheeran Avatar answered Mar 22 '26 16:03

jsheeran


For XMLUnit 2.x you wouldn't use DifferenceEvaluator but an "attribute filter" like in

DiffBuilder b = DiffBuilder.compare(some-onput)
    .withTest(some-test)
    .withAttributeFilter(a -> {
        QName attrName = Nodes.getQName(a);
        return !a.equals(new QName("schemaVS"))
            && !a.equals(new QName(schema-uri-of-a, "schemaLocate"));
    })
    ...

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!