Giter Club home page Giter Club logo

xmlunit.net's Introduction

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

XMLUnit 1.x is no longer maintained, you can still find the old forum over at sourceforge and we still use the sourceforge provided mailing list.

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 want to use Input.fromJaxb - i.e. you want to serialize plain Java objects to XML as input - then you may also need to add a dependency on the JAXB implementation. For more details see the User's Guide.

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.

xmlunit.net's People

Contributors

bodewig avatar brabenetz avatar cas-tobias avatar cd21h avatar jawn avatar joephayes avatar milkyware avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xmlunit.net's Issues

Ignoring the sequence of child nodes doesn't work

I am getting 4 differences in this piece of code. Although I hope to get that they are identical

var xml1 = "<A><B>1</B><C>2</C></A>";
var xml2 = "<A><C>2</C><B>1</B></A>";

var source1 = Input.FromString(xml1).Build();
var source2 = Input.FromString(xml2).Build();

var diff = DiffBuilder
	.Compare(source1)
	.WithTest(source2)
	.WithDifferenceEvaluator(DifferenceEvaluators.Chain(
		DifferenceEvaluators.Default,
		DifferenceEvaluators.DowngradeDifferencesToSimilar(ComparisonType.CHILD_NODELIST_SEQUENCE)))
	.CheckForSimilar()
	.Build();

Download Zip and Build

First all, thanks for your hard work on this project. It sounds great.

When I download the Zip file on a virgin machine, unzip and load the project, it comes up with 61 errors and 7 warnings when built.

It would be even more awesome to be able to download an install without having to do a build, but if that isn't the case, then it would be good if the build would work on a virgin machine.

want to ignore sequence if child node have attribute

i want to ignore result that first childnode have difference index between control and test like

<Document>
      <a>a</a>
      <a b="a">a</a>
</Document>

<Document>
      <a b="a">a</a>
      <a>a</a>
</Document>

DiffBuilder.Compare("<Document><a>a</a><a b=\"a\">a</a></Document>").WithTest("<Document><a b=\"a\">a</a><a>a</a>></Document>")
                .IgnoreWhitespace().WithNodeMatcher(new DefaultNodeMatcher(ElementSelectors.ByName)).Build();

Not sure am i set NodeMatcher correct or not?

Support for NUnit4

When updating to use NUnit 4.0.1 the following exception occurs:
System.TypeLoadException : Method 'get_Description' in type 'Org.XmlUnit.Constraints.CompareConstraint' from assembly 'xmlunit-nunit3-constraints, Version=2.9.2.240, Culture=neutral, PublicKeyToken=e7d7e3088fd452f6' does not have an implementation.

NUnit4 requires constraints to have a Description getter.

Permit XML definition of white space

I am using XML Unit 2.9.2 within the context of a .NET 4.72 application.

The method NormalizeWhitespace() is keyed to the Unicode property Zs, which targets more than a dozen characters. But the specifications for XML define white space as only four characters: x9, xA, xD, x20, and that's the basis for standard technologies in the XML stack (e.g., XPath).

I can see the utility for the current XML Unit approach to whitespace, but Iโ€™m in a position where I need to use the more restrictive official XML definition. Could XML Unit 2 and 3 be enhanced to allow users to choose between definitions of whitespace?

NodeFilter should apply to more nodes

Currently NodeFilter is not applied to XmlDocumentType so you cannot suppress the comparisons. There may be even more XmlNodes missing, a cursory look through DOMDifferenceEngine says it probably is the only one but a second pair of eyes won't hurt. I don't think there is any good reason to apply it to XmlDocument itself as this would simply skip all comparisons altogether.

See also xmlunit/xmlunit#116 which may provide a solution that "just" need to get ported.

bug in get xpath of node

it's have bug that will navigate to wrong child when apply node filter

in Org.XmlUnit.Diff
DOMDifferenceEngine
function
UnmatchedControlNodes
and
UnmatchedTestNodes

the problem is that NavigateToChild was passed by index of List
that was filtered out
it must get correct index before pass to NavigateToChild
may be add something like
Array.IndexOf(testList[i].ParentNode.ChildNodes.Cast().ToArray(),testList[i])

bug example

var aa= DiffBuilder.Compare("<Document><Section><Binding /><Binding /><Finding /><Finding /><Finding /><Finding /><Finding /><Finding /><Finding /></Section></Document>")
.WithTest("<Document><Section><Binding /><Binding /><Finding /><Finding /><Finding /><Finding /><Finding /><Finding /></Section></Document>")
.IgnoreWhitespace()
.WithNodeFilter(node =>  "Document,Section,Finding".Split(',').Contains(node.Name))
.WithNodeMatcher(new DefaultNodeMatcher(ElementSelectors.ByNameAndText)).Build();

xml diffwith whitespaces

Faced that DiffBuilder ignores whitespaces between xml nodes and returns 'identical' in next example.
In case whitespace in 'uuid' value everything works as expected. I assume behaviour like Java https://stackoverflow.com/questions/5721290/does-xmlunit-have-an-assert-to-ignore-whitespace

var myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>";
var myTestXML = "<msg><uuid>0x00435A8C</uuid> </msg>";
var md = DiffBuilder.Compare(myControlXML).WithTest(myTestXML).CheckForIdentical().Build();

What am I doing wrong? I tried different versions starteed with 2.0.0

Release files

Hello,

I am totally new to this package.

I have been able to successfully compare two XML files based on the following code:

Diff myDiff = DiffBuilder.Compare(Input.FromFile(expected)).WithTest(Input.FromFile(result)).Build(); // assert Assert.False(myDiff.HasDifferences(), myDiff.ToString());

In the Dispose() method of my test class, I want to get rid of the tested file.

public void Dispose() { foreach (var testFile in testFiles) { File.Delete(testFile); } }

I get the folllowing error:

The process cannot access the file 'C:\Projects....xml' because it is being used by another process.

I see that DiffBuilder is not disposable.

BR
Nicolas

Wrong Constraint resolve

I think there is a problem with resolving constraint. Especially 'Not' constraints. Following test failed with message:
XML with XPath root/node Expected: <empty> But was: "someValue".
XML with XPath root/node Expected string length 3 but was 9. Strings differ at index 0. Expected: "ups" But was: "someValue" -----------^

It should be Expected: <not empty> for the first assertions and pass for second.

[Test]
public void XPathTest()
{
    var xml = @"<root><node>someValue</node></root>";

    Assert.That(xml, EvaluateXPathConstraint.HasXPath("root/node", Is.Not.Empty));
    Assert.That(xml, EvaluateXPathConstraint.HasXPath("root/node", Is.Not.EqualTo("ups")));
}

I've made a simple change by adding Resolve() to valueConstraint. In this cases, it helps. I'm not familiar with custom constraints in NUnit and don't know if it's appropriate solution that cover all cases.

public static EvaluateXPathConstraint HasXPath(string xPath, IConstraint valueConstraint)
{
    return new EvaluateXPathConstraint(xPath, valueConstraint.Resolve());
}

Assembly version conflict in XMLUnit.NUnit3.Constraints

Steps to reproduce:

  1. Create new C# project in VS2015.
  2. Install XMLUnit.NUnit3.Constraints via NuGet.
  3. Try to call CompareConstraint.IsIdenticalTo:
namespace ClassLibrary1
{
    using NUnit.Framework;
    using Org.XmlUnit.Constraints;

    [TestFixture]
    public class Class1
    {
        [Test]
        public void Test()
        {
            Assert.That("<foo/>", CompareConstraint.IsIdenticalTo("<bar/>"));
        }
    }
}

Error:

Error CS1705  Assembly 'xmlunit-nunit3-constraints' with identity 'xmlunit-
nunit3-constraints, Version=2.2.0.90, Culture=neutral,
PublicKeyToken=e7d7e3088fd452f6' uses 'nunit.framework, Version=3.0.5813.39033,
Culture=neutral, PublicKeyToken=2638cd05610744eb' which has a higher version
than referenced assembly 'nunit.framework' with identity 'nunit.framework,
Version=3.0.5813.39031, Culture=neutral, PublicKeyToken=2638cd05610744eb'

Nuget.org package

I've uploaded the xmlunit-core nuget package to nuget.org so I can reference it in a project instead of having to use a lib folder for the dll.

It's sat here: https://www.nuget.org/packages/xmlunit-core/2.0.0-alpha-01
and here: https://www.nuget.org/packages/xmlunit-constraints/2.0.0-alpha-01

I can transfer ownership of the nuget.org ID/package if you like, or if you have no plans to put it onto nuget.org I can change the project ID on nuget.org, either way it's probably best you own the original as I won't be updating it using a CI or automated build script so it could get out of date..

Inputs created from XmlDocument with "PreserveWhitespace = true" generate unexpected differences.

Hello!

First of all, thanks for the great library!

Maybe this is intentional, but I just spent way too much time figuring out why any 3 of the whitespace ignore rules were not working and were in fact returning twice the differences than w/o any additional rules.

Turns out, if you create XmlDocument with PreserveWhitespace set to true and use that as input source, then the whitespace rules don't work.

I've modified one of the test cases:

[Test]
public void TestDiff_withIgnoreWhitespaces_shouldSucceed() {
    // prepare testData
    string controlXml = "<a><b>Test Value</b></a>";
    string testXml = "<a>\n <b>\n  Test Value\n </b>\n</a>";
    var controlDoc = new XmlDocument
    {
        PreserveWhitespace = true
    };
    controlDoc.LoadXml(controlXml);
    var testDoc = new XmlDocument
    {
        PreserveWhitespace = true
    };
    testDoc.LoadXml(testXml);

    // run test
    var myDiff = DiffBuilder.Compare(Input.FromDocument(controlDoc).Build())
        .WithTest(Input.FromDocument(testDoc).Build())
        .IgnoreWhitespace()
        .Build();

    // validate result
    Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString());
}

I guess I would have expected that any of the whitespace ignore rules would take precedence over PreserveWhitespace setting.

System.Xml.XmlException with undeclared prefix

The DiffBuilder.Build throw a System.Xml.XmlException when passing an XML string that contains an undeclared prefix to Input.FromString.

Stack Trace:
System.Xml.XmlTextReaderImpl.Throw(Exception e)
System.Xml.XmlTextReaderImpl.LookupNamespace(NodeData node)
System.Xml.XmlTextReaderImpl.ElementNamespaceLookup()
System.Xml.XmlTextReaderImpl.ParseElement()
System.Xml.XmlTextReaderImpl.ParseDocumentContent()
System.Xml.XmlTextReaderImpl.Read()
System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
System.Xml.XmlDocument.Load(XmlReader reader)
Org.XmlUnit.Util.Convert.ToDocument(ISource s, Boolean prohibitDTD, XmlResolver resolver)
Org.XmlUnit.Util.Convert.ToDocument(ISource s, Boolean prohibitDTD)
Org.XmlUnit.Util.Convert.ToDocument(ISource s)
Org.XmlUnit.Input.WhitespaceStrippedSource..ctor(ISource originalSource)
Org.XmlUnit.Builder.DiffBuilder.Wrap(ISource source)
Org.XmlUnit.Builder.DiffBuilder.Build()

Repro:

[Fact]
public void Test01()
{
    //	Arrange
    var xml1 = "<Test:Element>Nothing Here</Test:Element>";
    bool result;

    //	Act
    var xmlDiff = DiffBuilder.Compare(Input.FromString(xml1))
        .WithTest(Input.FromString(xml1))
        .IgnoreWhitespace()
        .NormalizeWhitespace()
        .CheckForSimilar()
        .Build();   //  Throw an exception

    xmlDiff.TestSource.Dispose();
    xmlDiff.ControlSource.Dispose();

    //	Assert
    Assert.True(!xmlDiff.HasDifferences());
}

We should be able to compare XML fragments. Please, advise how to handle such situation.

Elements with different namespace prefix are detected as DIFFERENT instead of SIMILAR

When comparing these two XMLs:

// Actual = <Root xmlns:x=""http://namespace.com""><x:Elem></x:Elem><x:Elem2></x:Elem2></Root>
// Expected = <Root xmlns:y=""http://namespace.com""><y:Elem></y:Elem><y:Elem2></y:Elem2></Root>

with "similar" behavior, it should return no differences. But it does report:

Expected element tag name 'x:Elem' but was 'y:Elem' - comparing <x:Elem...> at /Root[1]/Elem[1] to <y:Elem...> at /Root[1]/Elem[1] (DIFFERENT), Expected element tag name 'x:Elem2' but was 'y:Elem2' - comparing <x:Elem2...> at /Root[1]/Elem2[1] to <y:Elem2...> at /Root[1]/Elem2[1] (DIFFERENT)

Encountered in v2.5. @bodewig has already located the bug, see second-to-last post in xmlunit/user-guide#12 for details.

Best regards,
D.R.

Assembly version conflict

Project type: C# library
Target Framework: 4.6
NUnit: 3.0.1 (3.0.5813.39031)
XMLUnit: 2.5.1

Similar issue: #20

App.config assembly redirect:

<dependentAssembly>
    <assemblyIdentity name="nunit.framework" publicKeyToken="2638cd05610744eb" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-999.999.999.999" newVersion="3.0.5813.39031"/>
</dependentAssembly>

Error message:
Severity Code Description Project File Line Suppression State Error CS1705 Assembly 'xmlunit-nunit3-constraints' with identity 'xmlunit-nunit3-constraints, Version=2.5.1.121, Culture=neutral, PublicKeyToken=e7d7e3088fd452f6' uses 'nunit.framework, Version=3.0.5813.39033, Culture=neutral, PublicKeyToken=2638cd05610744eb' which has a higher version than referenced assembly 'nunit.framework' with identity 'nunit.framework, Version=3.0.5813.39031, Culture=neutral, PublicKeyToken=2638cd05610744eb' SDM.HPCPost.Test

Despite the indication assembly redirect I still have this error. What else can I try? I tried unloading, rebuilding project - some tricks around Visual Studio but without effect. Unfortunately upgrading Nunit version it's not an option for now.

Build should target appropriate framework (.NET 3.5)

.NET 3.5 is the minimum required framework version (because of LINQ). What does this mean for Mono? Is Mono 3.5 the equivalent framework?

Change NuGet package to deliver assemblies into appropriate framework folders.

Create and clarify milestones and roadmap

Hello,

Thanks for this useful project!

If I see it correctly, the project is currently in alpha state. What needs to happen to get it to beta and release states?

Greetings,

Bernard

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.