XMLUnit for Java 2.x

Overview

XMLUnit for Java 2.x

Maven Central

Build Status XMLUnit 2.x for Java Coverage Status

XMLUnit is a library that supports testing XML output in several ways.

XMLUnit 2.x is a complete rewrite of XMLUnit and actually doesn't share any code with XMLUnit for Java 1.x.

Some goals for XMLUnit 2.x:

  • create .NET and Java versions that are compatible in design while trying to be idiomatic for each platform
  • remove all static configuration (the old XMLUnit class setter methods)
  • focus on the parts that are useful for testing
    • XPath
    • (Schema) validation
    • comparisons
  • be independent of any test framework

Even though active development happens for XMLUnit 2.x, XMLUnit 1.x for Java is still supported and will stay at sourceforge.

Documentation

Help Wanted!

If you are looking for something to work on, we've compiled a list of known issues.

Please see the contributing guide for details on how to contribute.

Latest Release

The latest releases are available as GitHub releases or via Maven Central.

The core library is

<dependency>
  <groupId>org.xmlunit</groupId>
  <artifactId>xmlunit-core</artifactId>
  <version>x.y.z</version>
</dependency>

SNAPSHOT builds

We are providing SNAPSHOT builds from Sonatypes OSS Nexus Repository, you need to add

<repository>
  <id>snapshots-repo</id>
  <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  <releases><enabled>false</enabled></releases>
  <snapshots><enabled>true</enabled></snapshots>
</repository>

to your Maven settings.

Examples

These are some really small examples, more is available as part of the user guide

Comparing Two Documents

Source control = Input.fromFile("test-data/good.xml").build();
Source test = Input.fromByteArray(createTestDocument()).build();
DifferenceEngine diff = new DOMDifferenceEngine();
diff.addDifferenceListener(new ComparisonListener() {
        public void comparisonPerformed(Comparison comparison, ComparisonResult outcome) {
            Assert.fail("found a difference: " + comparison);
        }
    });
diff.compare(control, test);

or using the fluent builder API

Diff d = DiffBuilder.compare(Input.fromFile("test-data/good.xml"))
             .withTest(createTestDocument()).build();
assert !d.hasDifferences();

or using Hamcrest with CompareMatcher

import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
...

assertThat(createTestDocument(), isIdenticalTo(Input.fromFile("test-data/good.xml")));

or using AssertJ with XmlAssert of the xmlunit-assertj module

import static org.xmlunit.assertj.XmlAssert.assertThat;
...

assertThat(createTestDocument())
            .and(Input.fromFile("test-data/good.xml"))
            .areIdentical();

or using AssertJ with XmlAssert of the xmlunit-assertj3 module

import static org.xmlunit.assertj3.XmlAssert.assertThat;
...

assertThat(createTestDocument())
            .and(Input.fromFile("test-data/good.xml"))
            .areIdentical();

Asserting an XPath Value

Source source = Input.fromString("<foo>bar</foo>").build();
XPathEngine xpath = new JAXPXPathEngine();
Iterable<Node> allMatches = xpath.selectNodes("/foo", source);
assert allMatches.iterator().hasNext();
String content = xpath.evaluate("/foo/text()", source);
assert "bar".equals(content);

or using Hamcrest with HasXPathMatcher, EvaluateXPathMatcher

assertThat("<foo>bar</foo>", HasXPathMatcher.hasXPath("/foo"));
assertThat("<foo>bar</foo>", EvaluateXPathMatcher.hasXPath("/foo/text()",
                                                           equalTo("bar")));

or using AssertJ with XmlAssert of the xmlunit-assertj module

import static org.xmlunit.assertj.XmlAssert.assertThat;
...

assertThat("<foo>bar</foo>").hasXPath("/foo");
assertThat("<foo>bar</foo>").valueByXPath("/foo/text()").isEqualTo("bar");

or using AssertJ with XmlAssert of the xmlunit-assertj3 module

import static org.xmlunit.assertj3.XmlAssert.assertThat;
...

assertThat("<foo>bar</foo>").hasXPath("/foo");
assertThat("<foo>bar</foo>").valueByXPath("/foo/text()").isEqualTo("bar");

Validating a Document Against an XML Schema

Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSources(Input.fromUri("http://example.com/some.xsd").build(),
                   Input.fromFile("local.xsd").build());
ValidationResult result = v.validateInstance(Input.fromDocument(createDocument()).build());
boolean valid = result.isValid();
Iterable<ValidationProblem> problems = result.getProblems();

or using Hamcrest with ValidationMatcher

import static org.xmlunit.matchers.ValidationMatcher.valid;
...

assertThat(createDocument(), valid(Input.fromFile("local.xsd")));

or using AssertJ with XmlAssert of the xmlunit-assertj module

import static org.xmlunit.assertj.XmlAssert.assertThat;
...

assertThat(createDocument()).isValidAgainst(Input.fromFile("local.xsd"));

or using AssertJ with XmlAssert of the xmlunit-assertj3 module

import static org.xmlunit.assertj3.XmlAssert.assertThat;
...

assertThat(createDocument()).isValidAgainst(Input.fromFile("local.xsd"));

Requirements

Starting with version 2.8.0 XMLUnit requires Java 7, which has always been the minimum requirement for the AssertJ module. All other modules in versions 2.0.0 to 2.7.0 required Java 6. The xmlunit-assertj3 module requires Java 8 as does AssertJ 3.x itself.

The core library provides all functionality needed to test XML output and hasn't got any dependencies. It uses JUnit 4.x for its own tests.

If you are using Java 9 or later the core also depends on the JAXB API. This used to be part of the standard class library but has been split out of it with Java 9.

If you want to use Input.fromJaxb - i.e. you want to serialize plain Java objects to XML as input - then you also need to add a dependency on the JAXB implementation. Starting with XMLUnit 2.6.4, xmlunit-core optionally depends on the JAXB reference implementation and its transitive dependencies. Starting with XMLUnit 2.8.0 the JAXB dependency requires the JakartaEE version of JAXB.

The core library is complemented by Hamcrest 1.x matchers and AssertJ assertions. There also exists a legacy project that provides the API of XMLUnit 1.x on top of the 2.x core library.

While the Hamcrest matchers are built against Hamcrest 1.x they are supposed to work with Hamcrest 2.x as well.

Starting with XMLUnit 2.8.1 there are two different AssertJ modules, xmlunit-assertj is the original implementation which is based on AssertJ 2.x and also works for AssertJ 3.x but uses reflection to deal with some changes in later versions of AssertJ. The xmlunit-assertj3 module requires at least AssertJ 3.18.1.

The xmlunit-assertj module depends on an internal package not exported by AssertJ's OSGi module and thus doesn't work in an OSGi context.

Another difference between the two AssertJ modules is the exception thrown if a comparison fails. xmlunit-assertj will try to throw a JUnit 4.x ComparisonFailure if the class is available and thus is best suited for tests using JUnit 4.x. xmlunit-assertj3 will try to throw an Open Test Alliance AssertionFailedError if the class is available and thus is better suited for tests using JUnit 5.x.

Checking out XMLUnit for Java

XMLUnit for Java uses a git submodule for test resources it shares with XMLUnit.NET. You can either clone this repository using git clone --recursive or run git submodule update --init inside your fresh working copy after cloning normally.

If you have checked out a working copy before we added the submodule, you'll need to run git submodule update --init once.

Building

XMLUnit for Java builds using Apache Maven 3.x, mainly you want to run

$ mvn install

in order to compile all modules and run the tests.

Comments
  • ElementSelectors.byNameAndText doesnt ignore the order of nodes

    ElementSelectors.byNameAndText doesnt ignore the order of nodes

    Hi,

    I am quite impressed with the library and its documentation. Thanks for providing all the support. I have seen your issues https://github.com/xmlunit/xmlunit/issues/77 suggesting to use ElementSelectors.byNameAndText for ignoring the order of elements.

    However if i have XML's something like this, the XMLUnit comparison fails to believe that its the same XML structure.

    XML Control:

    <root>
    <parent><line>
    <segment>L</segment>
    </line>
    <line>
    <segment>K</segment>
    </line>
    <line>
    <segment>P</segment>
    </line>
    </root>
    
    <root>
    <parent><line>
    <segment>P</segment>
    </line>
    <line>
    <segment>K</segment>
    </line>
    <line>
    <segment>L</segment>
    </line>
    </root>
    

    Here is my code:

    Diff myDiff = DiffBuilder.compare(control).withTest(test).checkForSimilar(). withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)).build(); if(myDiff.hasDifferences()) Iterator iterator = myDiff.getDifferences().iterator(); while(iterator.hasNext()) Difference diff = iterator.next(); System.out.println(diff.getComparison().toString) }

    Please let me know what am i missing here, essentially these two structures of XML are same in different Line element order.

    Also, I wanted to ignore white space between elements, i have considered using normalizeWhiteSpace and ignoreWhiteSpace API but they essentially remove the spaces from the text content as well. Below both XML's are same except element 'line' is in next time for one of the XML structure.

    <root>
    <parent><line>
    <segment>L</segment>
    </line>
    <line>
    <segment>K</segment>
    </line>
    <line>
    <segment>P</segment>
    </line>
    </root>
    
    <root>
    <parent>
    <line>
    <segment>P</segment>
    </line>
    <line>
    <segment>K</segment>
    </line>
    <line>
    <segment>L</segment>
    </line>
    </root>
    
    

    I really appreciate your help, I spent quite a bit of time figuring this out.

    question 
    opened by merajani 22
  • Comparing nodes with checkForSimilar and checkForIdentical

    Comparing nodes with checkForSimilar and checkForIdentical

    Hello again,

    Let's say I have these strings: String xml1 ="<persons><person><Id>1</Id><name><firstName>George</firstName><lastName>White</lastName></name></person><person><Id>2</Id><name><firstName>John</firstName><lastName>Black</lastName></name></person></persons>";

    String xml2 ="<persons><person><Id>2</Id><name><firstName>John</firstName><lastName>Black</lastName></name></person><person><name><firstName>George</firstName><lastName>White</lastName></name><Id>1</Id></person></persons>";

    I don't mind about the order of 'person' elements but I do mind about the order of the child nodes of 'person' element like the 'name' element that comes before the 'Id' element in the xml2 string.

    I figured I would use this:

    .withNodeMatcher(new DefaultNodeMatcher(conditionalBuilder()
                        .whenElementIsNamed("person").thenUse(byXPath("./Id", byNameAndText))
                        .elseUse(byNameAndText).build()))
                        .withDifferenceEvaluator(DifferenceEvaluators.chain(
                           DifferenceEvaluators.Default,            
    DifferenceEvaluators.upgradeDifferencesToDifferent(ComparisonType.CHILD_NODELIST_SEQUENCE) ))
    .checkForSimilar()
    .build();
    

    but it just overrides the difference outcome of comparison of 'person' nodes not its children.

    What am I missing here?

    question 
    opened by michailangelo 20
  • Not running combined with Saxon

    Not running combined with Saxon

    Hey, I run into trouble after importing Saxon 9 HE. The code works without importing the jar of Saxon. After importing it thows the exception. It is only if I try to use ignoreWhitespace. Any idea for a workaround. Or is this an issue?

    Thanks for your help!

    Diff diff_list = DiffBuilder.compare(Input.fromString(controlstr)).withTest(Input.fromString(teststr)) .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)) .checkForSimilar().**ignoreWhitespace**().ignoreComments() .withComparisonController(ComparisonControllers.Default) .build();

    java.lang.ClassCastException: net.sf.saxon.value.ObjectValue cannot be cast to net.sf.saxon.om.NodeInfo at net.sf.saxon.s9api.DocumentBuilder.wrap(DocumentBuilder.java:509) at net.sf.saxon.s9api.XsltTransformer.setSource(XsltTransformer.java:214) at net.sf.saxon.jaxp.TransformerImpl.transform(TransformerImpl.java:89) at org.xmlunit.transform.Transformation.transformTo(Transformation.java:186) at org.xmlunit.transform.Transformation.transformToDocument(Transformation.java:220) at org.xmlunit.input.CommentLessSource.<init>(CommentLessSource.java:45) at org.xmlunit.builder.DiffBuilder.wrap(DiffBuilder.java:389) at org.xmlunit.builder.DiffBuilder.build(DiffBuilder.java:368) at org.artdecor.TemplateDifference.compare(TemplateDifference.java:118)

    invalid 
    opened by maschhoff 20
  • OSGI - org.assertj.core.internal is not exposed and can therefor not be used.

    OSGI - org.assertj.core.internal is not exposed and can therefor not be used.

    When using the xmlunit-assertj module in an OSGI environment tests fail because of the use of classes in the org.assert.core.internal package. This package is not marked as exposed and can therefor not be accessed.

    The only use for this import seems to be the Failures class. So far I haven't found a way to avoid it so I'm also creating an issue with the assertj-core module to request it to be moved to the util package.

    See https://github.com/assertj/assertj-core/issues/2026

    AssertJ Support AssertJ 3.x Support 
    opened by Zegveld 18
  • Gradle fails to resolve dependency net.bytebuddy:byte-buddy

    Gradle fails to resolve dependency net.bytebuddy:byte-buddy

    The following build.gradle snippet

    dependencies {
        testImplementation platform("org.junit:junit-bom:5.6.2")
        testImplementation 'org.junit.jupiter:junit-jupiter-api'
        testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
        testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
        testRuntimeOnly 'org.junit.platform:junit-platform-runner'
        
        testImplementation "org.assertj:assertj-core:3.16.1"
        testImplementation "org.xmlunit:xmlunit-core:2.7.0"
        testImplementation "org.xmlunit:xmlunit-assertj:2.7.0"
    }
    

    fails to resolve Byte Buddy with the following error:

    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Execution failed for task ':server:compileTestJava'.
    > Could not resolve all files for configuration ':server:testCompileClasspath'.
       > Could not find net.bytebuddy:byte-buddy:.
         Required by:
             project :server > org.xmlunit:xmlunit-assertj:2.7.0
    

    Which version of Byte Buddy do I need to include?

    assertj-core itself depends on Byte Buddy already but shades the dependency into it's own jar.

    AssertJ Support 
    opened by thokuest 15
  • Project targets at Java 7, but requires Java 8 deps when runs at Java 9+

    Project targets at Java 7, but requires Java 8 deps when runs at Java 9+

    I am working on Maven Doxia and recently upgraded xmlunit-core, the GH action tells me this: https://github.com/apache/maven-doxia/runs/4827147809?check_suite_focus=true#step:5:1729

    The project is still targeted at Java 7, so is xmlunit. We test with multiple JDK versions, as soon as Java 11 is used a Java 8 dependency is sourced. This contradicts the project's target at 7. Enforcer rejects the build. While I could upgrade to Java 8, but for the wrong reasons.

    This snippet does not mention that actually Java 8 bytecode level will be required:

    If you are using Java 9 or later the core also depends on the JAXB API. This used to be part of the standard class library but has been split out of it with Java 9.
    
    If you want to use Input.fromJaxb - i.e. you want to serialize plain Java objects to XML as input - then you also need to add a dependency on the JAXB implementation. Starting with XMLUnit 2.6.4, xmlunit-core optionally depends on the JAXB reference implementation and its transitive dependencies. Starting with XMLUnit 2.8.0 the JAXB dependency requires the JakartaEE version of JAXB.
    

    Is GlassFish JAXB from javax namespace in version 2.x not more than enough for this project?

    core build documentation 
    opened by michael-o 14
  • Embedded/inline matcher support

    Embedded/inline matcher support

    How about supporting embedded/inline matcher in XMLUnit?

    For example, suppose we have

    Expected (control) XML '<elem1><elem11>${xml-unit.any-number}</elem11></elem1>'
    
    Actual (test) XML #1 '<elem1><elem11>123</elem11></elem1>'
    
    Actual (test) XML #2 '<elem1><elem11>abc</elem11></elem1>'
    

    We consider actual XML #1 equal to the expected XML, but actual XML #2 not equal to the expected XML.

    This is actually an idea from JsonUnit.

    I feel this feature really useful and powerful, especially with the Custom matchers support.

    enhancement help wanted placeholders 
    opened by zheng-wang 13
  • Default to not fetching DTDs from the network

    Default to not fetching DTDs from the network

    I found us having to workaround this one:

            // This is to disable DTD lookups on the internet         DocumentBuilderFactory dbf = XMLUnit.getControlDocumentBuilderFactory();         dbf.setFeature("http://xml.org/sax/features/validation", false);         dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);         dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    I think that by default, at least loading external DTDs should be disabled, since I prefer to have my tests reliably pass without external factors being able to trigger failures. (I don't particularly mind validation being left turned on for DTDs which are local... and am not entirely sure why we are disabling that as well.)

    enhancement core java-legacy 
    opened by hakanai 13
  • OutOfMemoryError when using XMLUnit

    OutOfMemoryError when using XMLUnit

    We see OOM Errors when using XML-Unit

    10:14:02  java.lang.OutOfMemoryError: Java heap space
    10:14:02      at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.getNodeObject (DeferredDocumentImpl.java:940)
    10:14:02      at com.sun.org.apache.xerces.internal.dom.DeferredElementNSImpl.synchronizeData (DeferredElementNSImpl.java:127)
    10:14:02      at com.sun.org.apache.xerces.internal.dom.ElementNSImpl.getLocalName (ElementNSImpl.java:307)
    10:14:02      at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.importNode (CoreDocumentImpl.java:1545)
    10:14:02      at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.importNode (CoreDocumentImpl.java:1750)
    10:14:02      at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.importNode (CoreDocumentImpl.java:1750)
    10:14:02      at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.importNode (CoreDocumentImpl.java:1750)
    10:14:02      at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.cloneNode (CoreDocumentImpl.java:405)
    10:14:02      at com.sun.org.apache.xerces.internal.dom.DocumentImpl.cloneNode (DocumentImpl.java:181)
    10:14:02      at org.xmlunit.util.Nodes.stripWhitespace (Nodes.java:93)
    10:14:02      at org.xmlunit.input.WhitespaceStrippedSource.<init> (WhitespaceStrippedSource.java:40)
    10:14:02      at org.xmlunit.builder.DiffBuilder.wrap (DiffBuilder.java:441)
    10:14:02      at org.xmlunit.builder.DiffBuilder.build (DiffBuilder.java:430)
    

    Is there anything one must do to "clear" DiffBuilder instances so we probably acummulate memory?

    opened by laeubi 12
  • ByNameAndTextRecSelector and element order

    ByNameAndTextRecSelector and element order

    I'm trying to do matching where the element order of elements with different names may vary. In xmlunit 1 I used RecursiveElementNameAndTextQualifier, perhaps wrongly. In xmlunit 2, I thought the user guide is saying that ByNameAndTextRecSelector should work analogously, but I'm not successful. Here's a short test. Am I reading the user guide wrong, or perhaps it could use a clarification?

    import java.io.IOException;
    import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
    import org.xml.sax.SAXException;
    import org.xmlunit.builder.DiffBuilder;
    import org.xmlunit.builder.Input;
    import org.xmlunit.diff.ByNameAndTextRecSelector;
    import org.xmlunit.diff.DefaultNodeMatcher;
    
    public class Test {
    
        public static void main(String[] args) throws SAXException, IOException {
    
            final String xml1 = "<root><a/><b/></root>";
            final String xml2 = "<root><b/><a/></root>";  // Flip <a/> and <b/>
    
            // xmlunit 1
            org.custommonkey.xmlunit.Diff diff1 = new org.custommonkey.xmlunit.Diff(xml1, xml2);
            diff1.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
            System.out.println("diff1.similar(): " + diff1.similar());
    
            // xmlunit 2
            org.xmlunit.diff.Diff diff2 = DiffBuilder
                    .compare(Input.fromString(xml1))
                    .withTest(Input.fromString(xml2))
                    .checkForSimilar()
                    .withNodeMatcher(new DefaultNodeMatcher(new ByNameAndTextRecSelector()))
                    .build();
            System.out.println("diff2.hasDifferences(): " + diff2.hasDifferences());
            diff2.getDifferences().forEach(difference -> System.out.println(difference));
        }
    }
    
    question core 
    opened by dhalbert 12
  • Comparing XML files ignoring elements attribute Order

    Comparing XML files ignoring elements attribute Order

    HI All,

    Iam new to this field and has been assigned with a challenging task. I have 2 XML files (namely Test1 & Test 2 as mentioned below). And i need to compare these xml files using java and return boolean value as true if there are no differences. And the challenge here is the Second Xml file (Test2.xml) the elements order is always jumbled I tried XMLUnit2 for comparing the 2 xml strings but it is failing if there are multiple parent nodes or large xml.

    Test1.Xml:
    
    <PACKINGS>
        <PACKING>
          <TYPE>CCST</TYPE>
          <ORDERNUM>810000510</ORDERNUM>
          <SVCTAGS>
            <SVCTAG>
              <SVCTAGTYPE>DRAGON</SVCTAGTYPE>
              <SVCTAGNUMBER>768100005105001</SVCTAGNUMBER>
              <TIENUMBER>1</TIENUMBER>
              <BOXID>768100005105001</BOXID>
              <LENGTH>4</LENGTH>
              <WIDTH>5</WIDTH>
              <HEIGHT>10</HEIGHT>
              <PARTS>
                <PART>
                  <PARTNUMBER>RKH5D</PARTNUMBER>
                  <PARTQTY>10</PARTQTY>
                </PART>
              </PARTS>
            </SVCTAG>
            <SVCTAG>
              <SVCTAGTYPE>DRAGON</SVCTAGTYPE>
              <SVCTAGNUMBER>768100005105002</SVCTAGNUMBER>
              <TIENUMBER>2</TIENUMBER>
              <BOXID>768100005105002</BOXID>
              <LENGTH>4</LENGTH>
              <WIDTH>5</WIDTH>
              <HEIGHT>10</HEIGHT>
              <PARTS>
                <PART>
                  <PARTNUMBER>FHMTN</PARTNUMBER>
                  <PARTQTY>10</PARTQTY>
                </PART>
              </PARTS>
            </SVCTAG>
          </SVCTAGS>
        </PACKING>
      </PACKINGS>
    
    
    Test2.Xml:
    
      <PACKINGS>
          <PACKING>
            <TYPE>CCST</TYPE>
            <ORDERNUM>810000510</ORDERNUM>
            <SVCTAGS>
            <SVCTAG>
            <SVCTAGTYPE>DRAGON</SVCTAGTYPE>
            <SVCTAGNUMBER>768100005105002</SVCTAGNUMBER>
            <TIENUMBER>2</TIENUMBER>
            <BOXID>768100005105002</BOXID>
            <LENGTH>4</LENGTH>
            <WIDTH>5</WIDTH>
            <HEIGHT>10</HEIGHT>
          <PARTS>
            <PART>
             <PARTNUMBER>FHMTN</PARTNUMBER>
             <PARTQTY>10</PARTQTY>
             </PART>
           </PARTS>
          </SVCTAG>
          <SVCTAG>
            <SVCTAGTYPE>DRAGON</SVCTAGTYPE>
            <SVCTAGNUMBER>768100005105001</SVCTAGNUMBER>
            <TIENUMBER>1</TIENUMBER>
            <BOXID>768100005105001</BOXID>
            <LENGTH>4</LENGTH>
            <WIDTH>5</WIDTH>
            <HEIGHT>10</HEIGHT>
          <PARTS>
           <PART>
            <PARTNUMBER>RKH5D</PARTNUMBER>
            <PARTQTY>10</PARTQTY>
            </PART>
          </PARTS>
         </SVCTAG>
        </SVCTAGS>
       </PACKING>
      </PACKINGS>
    
    

    package com.com.java; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.*;

    import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.XMLAssert; import org.testng.annotations.Test; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.builder.Input; import org.xmlunit.diff.DefaultNodeMatcher; import org.xmlunit.diff.ElementSelectors; import org.xmlunit.matchers.CompareMatcher;

    public class TestNg { @Test public void testXmlUnit() { String ControlXML = "CCST810000510DRAGON76810000510500227681000051050024510DRAGON76810000510500117681000051050014510RKH5D10"; String testXml = "CCST810000510DRAGON76810000510500117681000051050014510DRAGON76810000510500227681000051050024510FHMTN10"; assertThat(testXml, CompareMatcher.isSimilarTo(ControlXML).ignoreWhitespace().normalizeWhitespace().withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText, ElementSelectors.byName)));

    }
    }

    question 
    opened by vramsprsk 11
  • Relationship between DiffBuilder and JAXPXPathEngine

    Relationship between DiffBuilder and JAXPXPathEngine

    I have currently trouble because of very slow comparisons with the DiffBuilder class. Changing the used xpath engine could be helpful but I am struggling with the relationship between DiffBuilder and JAXPXPathEngine. Into the second class I can pass a custom XPathFactory (like Saxon), but I do not see a possibility to propagate this to the DiffBuilder. Am I missing something? What is the relationship between the two classes, or is there just no relationship? Then I would need a different approach.

    Thanks for help, I am currently a little bit confused.

    enhancement question core 
    opened by wiedehoeft 6
  • xml placeholder is not ignoring child nodes present under parent node.

    xml placeholder is not ignoring child nodes present under parent node.

    This issue we faced while API Test Automation design. In our web service testing we trigger the API request (north bound) and checks the downstream request formed by application code. We use mocked backend using wiremock. Wiremock has capability equalToXml which support the matching of incoming request and expected request and thus test is validated.

    Issue is while xml comparison using ${xmlunit.ignore} placeholder we are able to ignore the values from single node but not able to ignore anything entirely present under a particular node if that node has child nodes.

    This would help in xml comparisons when some part in request is unknown or under development or its dynamic and of no interest for comparison etc. Issues was raised on wiremock project #1741but later found that wiremock is using xmlunit as dependency.

    Example:

    <device>
    <deviceType>Mobile</deviceType>
    <IMEI>12345678912345</IMEI>
    <deviceName>My Samsung</deviceName>
    </device>
    
    
    Above incoming request will match with
    
    <device>
    <deviceType>Mobile</deviceType>
    <IMEI>${xmlunit.ignore}</IMEI>
    <deviceName>${xmlunit.ignore}</deviceName>
    </device>
    
    /*****************************************************************/
    
    But incoming request
    
    <device>
    <deviceType>Mobile</deviceType>
    <deviceDetails>
         <IMEI>12345678912345</IMEI>
         <deviceName>My Samsung</deviceName>
    </deviceDetails>
    </device>
    
    OR
    
    <device>
    <deviceType>Mobile</deviceType>
    <deviceDetails>
         <IMEI>12345678912345</IMEI>
         <deviceName>My Samsung</deviceName>
         <deviceSerialNumber>XYZ-123</deviceSerialNumber>
    </deviceDetails>
    </device>
    
    does not match with 
    
    <device>
    <deviceType>Mobile</deviceType>
    <deviceDetails>${xmlunit.ignore}</deviceDetails>
    </device>
    
    enhancement help wanted placeholders 
    opened by Devendra-Gawde 6
  • Migration to Java 8

    Migration to Java 8

    XmlUnit core project now compiled to Java 7 sources. Java 7 was released ten years ago and now it's just a part of a history. Java versions usage statistics shows that's the most popular Java version in 2020 is a Java 8. Oracle doesn't support Java 7 anymore as first class citizen. So I think that it's time to migrate XmlUnit to Java 8.

    Migration to Java 8 will allow to use new cool features like lambda expressions, streams, datetime api etc. Some of these features could be a part of XmlUnit API. Also migration to Java 8 will open a way for usage of new version of internal dependencies. Like JUnit Jupiter 5 instead of JUnit 4.

    Another point: it's strange that part of this project (like xmlunit-core) is run on Java 7+ and another part runs only on Java 8+ (xmlunit-assertj3).

    enhancement core 
    opened by Boiarshinov 5
  • Provide unordered collection diff support

    Provide unordered collection diff support

    The current implementation of Diff looks to have an assumption that collection is ordered and doesn't look there's any switch to the assumption so that unordered collections can be handled.

    It would be nice to provide unordered collection diff based on XML schema.

    This is a test to illustrate what I'm trying to suggest: https://github.com/izeye/samples-java-branches/blob/master/src/test/java/learningtest/org/xmlunit/diff/DiffTests.java#L62-L82

    enhancement help wanted core 
    opened by izeye 8
  • Allow injection of DTD set into documents

    Allow injection of DTD set into documents

    This is a follow up ticket for the discussion started in https://github.com/xmlunit/user-guide/issues/9

    It would be nice to have an API that allowed the DTD of a document to get manipulated or to inject an internal DTD. The legacy module contains an support for replacing a DTD in https://github.com/xmlunit/xmlunit/blob/master/xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/DoctypeInputStream.java

    One approach could be a custom Source implementation inside the input package. I'm not convinced we'd need support inside the Input builder.

    enhancement help wanted core 
    opened by bodewig 0
Releases(v2.9.0)
Owner
XMLUnit
XMLUnit 2.x - testing and comparing XML output for Java and .NET
XMLUnit
HATEOAS with HAL for Java. Create hypermedia APIs by easily serializing your Java models into HAL JSON.

hate HATEOAS with HAL for Java. Create hypermedia APIs by easily serializing your Java models into HAL JSON. More info in the wiki. Install with Maven

null 20 Oct 5, 2022
Never debug a test again: Detailed failure reports and hassle free assertions for Java tests - Power Asserts for Java

Scott Test Reporter for Maven and Gradle Get extremely detailed failure messages for your tests without assertion libraries, additional configuration

Dávid Csákvári 133 Nov 17, 2022
TCP Chat Application - Java networking, java swing

TCP-Chat-Application-in-Java TCP Chat Application - Java networking, java swing Java – Multithread Chat System Java Project on core Java, Java swing &

Muhammad Asad 5 Feb 4, 2022
A sample repo to help you handle basic auth for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to handle basic auth for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - htt

null 12 Jul 13, 2022
A sample repo to help you clear browser cache with Selenium 4 Java on LambdaTest cloud. Run your Java Selenium tests on LambdaTest platform.

How to clear browser cache with Selenium 4 Java on LambdaTest cloud Prerequisites Install and set environment variable for java. Windows - https://www

null 12 Jul 13, 2022
A sample repo to help you run automation test in incognito mode in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to run automation test in incognito mode in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - htt

null 12 Jul 13, 2022
A sample repo to help you handle cookies for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to handle cookies for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - https:

null 13 Jul 13, 2022
A sample repo to help you set geolocation for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to set geolocation for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - https

null 12 Jul 13, 2022
A sample repo to help you capture JavaScript exception for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to capture JavaScript exception for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Wi

null 12 Jul 13, 2022
A sample repo to help you find an element by text for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to find an element by text for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows

null 12 Jul 13, 2022
A sample repo to help you emulate network conditions in Java-selenium automation test on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to emulate network conditions in Java-selenium automation test on LambdaTest Prerequisites Install and set environment variable for java. Windows

null 12 Jul 13, 2022
Awaitility is a small Java DSL for synchronizing asynchronous operations

Testing asynchronous systems is hard. Not only does it require handling threads, timeouts and concurrency issues, but the intent of the test code can

Awaitility 3.3k Dec 31, 2022
Java binding for Hoverfly

Hoverfly Java - Easy Creation of Stub Http Servers for Testing A Java native language binding for Hoverfly, a Go proxy which allows you to simulate ht

null 148 Nov 21, 2022
Java DSL for easy testing of REST services

Testing and validation of REST services in Java is harder than in dynamic languages such as Ruby and Groovy. REST Assured brings the simplicity of usi

REST Assured 6.2k Dec 31, 2022
Library that allows tests written in Java to follow the BDD style introduced by RSpec and Jasmine.

J8Spec J8Spec is a library that allows tests written in Java to follow the BDD style introduced by RSpec and Jasmine. More details here: j8spec.github

J8Spec 45 Feb 17, 2022
A modern testing and behavioural specification framework for Java 8

Introduction If you're a Java developer and you've seen the fluent, modern specification frameworks available in other programming languages such as s

Richard Warburton 250 Sep 12, 2022
A library for setting up Java objects as test data.

Beanmother Beanmother helps to create various objects, simple and complex, super easily with fixtures for testing. It encourages developers to write m

Jaehyun Shin 113 Nov 7, 2022
Java fake data generator

jFairy by Devskiller Java fake data generator. Based on Wikipedia: Fairyland, in folklore, is the fabulous land or abode of fairies or fays. Try jFair

DevSkiller 718 Dec 10, 2022