When comparing XML files, how to get detailed response using XMLUnit 2.8.2

422 Views Asked by At

I need help with ComparisonFormatter. I've not been able to find many examples on ComparisonFormatter online.

I'm using XMLUnit 2.8.2. I'm trying to compare two xml files regardless of their order. The code below works fine when responses are in order or are not in order. The problem is when the response have mismatch. For example, when INFOId is equal to FQ001 in control response and FA001 in test response. In this case I get the response "[Expected child 'INFO' but was 'null' - comparing <INFO...> at ...etc" After some research, I found out that I should use ComparisonFormatter to get more detailed response. Can someone please give me some examples of how to use ComparisonFormatter? If using ComparisonFormatter is not the right approach, then please guide me to right direction.

String controlXml = "<Return><INFO><Area>0</Area><INFOId>AA23414</INFOId></INFO><INFO><Area>0</Area><INFOId>FQ001</INFOId></INFO></Return>";
String testXml    = "<Return><INFO><Area>0</Area><INFOId>FA001</INFOId></INFO><INFO><Area>0</Area><INFOId>AA23414</INFOId></INFO></Return>";



         DiffBuilder builder = DiffBuilder.compare(controlXml).withTest(testXml)
                    .checkForSimilar()
                    .ignoreWhitespace()
                    .normalizeWhitespace()
                    .ignoreComments()
                    .checkForSimilar()  
                    .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.conditionalBuilder()
                    .whenElementIsNamed("INFO")
                    .thenUse(ElementSelectors.byXPath("./INFOId", ElementSelectors.byNameAndText))
                            .elseUse(ElementSelectors.byName)
                    .build()));


        int i = 0;
        org.xmlunit.diff.Diff diff = builder.build();
        if (diff.hasDifferences()) 
        {                                       
            System.out.println(diff.getDifferences());               
                i++;
        }
        System.out.println("Size = " +i);

Thanks in advance! Any help will be appreciated.

1

There are 1 best solutions below

1
Thilo Schwarz On

Long time ago, I've got the same issue. xmlunit-2 has the option to order the nodes before comparing them.

    String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
    String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
    
    assertThat(testXml, 
      isSimilarTo(controlXml).withNodeMatcher(
      new DefaultNodeMatcher(ElementSelectors.byName)));