ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 485

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

XMLUnit Java User’s Guide

2 / 35

Example 1.1 Configuring JAXP via System Properties

System.setProperty("javax.xml.parsers.DocumentBuilderFactory",

"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

System.setProperty("javax.xml.parsers.SAXParserFactory",

"org.apache.xerces.jaxp.SAXParserFactoryImpl");

System.setProperty("javax.xml.transform.TransformerFactory",

"org.apache.xalan.processor.TransformerFactoryImpl");

You may want to read Section 2.4.1 for more details - in particular if you are using Java 1.4 or later.

Alternatively there are static methods on the XMLUnit class that can be called directly. The advantage of this approach is that you can specify a different parser class for control and test XML and change the current parser class at any time in your tests, should you need to make assertions about the compatibility of different parsers.

Example 1.2 Configuring JAXP via XMLUnit class

XMLUnit.setControlParser("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

XMLUnit.setTestParser("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

XMLUnit.setSAXParserFactory("org.apache.xerces.jaxp.SAXParserFactoryImpl");

XMLUnit.setTransformerFactory("org.apache.xalan.processor.TransformerFactoryImpl");

1.5Writing XML comparison tests

Let’s say we have two pieces of XML that we wish to compare and assert that they are equal. We could write a simple test class like this:

Example 1.3 A simple comparison test

public class MyXMLTestCase extends XMLTestCase { public MyXMLTestCase(String name) {

super(name);

}

public void testForEquality() throws Exception {

String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>"; String myTestXML = "<msg><localId>2376</localId></msg>"; assertXMLEqual("Comparing test xml to control xml",

myControlXML, myTestXML);

}

}

The assertXMLEqual test will pass if the control and test XML are either similar or identical. Obviously in this case the pieces of XML are different and the test will fail. The failure message indicates both what the difference is and the XPath locations of the nodes that were being compared:

Comparing test xml to control xml

 

...[different] Expected element tag name ’uuid’ but was ’localId’ - comparing <uuid

> at / -

...msg[1]/uuid[1] to <localId > at /msg[1]/localId[1]

 

 

 

When comparing pieces of XML, the XMLTestCase actually creates an instance of the Diff class. The Diff class stores the result of an XML comparison and makes it available through the methods similar() and identical(). The asser tXMLEqual() method tests the value of Diff.similar() and the assertXMLIdentical() method tests the value of

Diff.identical().

It is easy to create a Diff instance directly without using the XMLTestCase class as below:


XMLUnit Java User’s Guide

3 / 35

Example 1.4 Creating a Diff instance

public void testXMLIdentical()throws Exception { String myControlXML =

"<struct><int>3</int><boolean>false</boolean></struct>"; String myTestXML =

"<struct><boolean>false</boolean><int>3</int></struct>"; Diff myDiff = new Diff(myControlXML, myTestXML); assertTrue("XML similar " + myDiff.toString(),

myDiff.similar());

assertTrue("XML identical " + myDiff.toString(), myDiff.identical());

}

This test fails as two pieces of XML are similar but not identical if their nodes occur in a different sequence. The failure message reported by JUnit from the call to myDiff.toString() looks like this:

...[not identical] Expected sequence of child nodes ’0’ but was ’1’ - comparing <int

> at / -

...struct[1]/int[1] to <int > at /struct[1]/int[1]

 

 

 

For efficiency reasons a Diff stops the comparison process as soon as the first difference is found. To get all the differences between two pieces of XML an instance of the DetailedDiff class, a subclass of Diff, is required. Note that a Detailed Diff is constructed using an existing Diff instance.

Consider this test that uses a DetailedDiff:

Example 1.5 Using DetailedDiff

public void testAllDifferences() throws Exception {

String myControlXML = "<news><item id=\"1\">War</item>"

+"<item id=\"2\">Plague</item>"

+"<item id=\"3\">Famine</item></news>";

String myTestXML = "<news><item id=\"1\">Peace</item>"

+"<item id=\"2\">Health</item>"

+"<item id=\"3\">Plenty</item></news>";

DetailedDiff myDiff = new DetailedDiff(new Diff(myControlXML, myTestXML)); List allDifferences = myDiff.getAllDifferences(); assertEquals(myDiff.toString(), 2, allDifferences.size());

}

This test fails with the message below as each of the 3 news items differs between the control and test XML:

[different] Expected text value ’War’ but was ’Peace’ - comparing <item...>War</item> at /

-

news[1]/item[1]/text()[1] to <item...>Peace</item> at /news[1]/item[1]/text()[1]

 

[different] Expected text value ’Plague’ but was ’Health’ - comparing <item...>Plague</item

-

> at /news[1]/item[2]/text()[1] to <item...>Health</item> at /news[1]/item[2]/text()[1]

 

[different] Expected text value ’Famine’ but was ’Plenty’ - comparing <item...>Famine</item

-

> at /news[1]/item[3]/text()[1] to <item...>Plenty</item> at /news[1]/item[3]/text()[1]

 

expected <2> but was <3>

 

 

 

The List returned from the getAllDifferences() method contains Difference instances. These instances describe both the type4 of difference found between a control node and test node and the NodeDetail of those nodes (including the XPath location of each node). Difference instances are passed at runtime in notification events to a registered DifferenceList ener, an interface whose default implementation is provided by the Diff class.

However it is possible to override this default behaviour by implementing the interface in your own class. The IgnoreTextAnd AttributeValuesDifferenceListener class is an example of how to implement a custom DifferenceListener.

4 A full set of prototype Difference instances - one for each type of difference - is defined using final static fields in the DifferenceConstants class.


XMLUnit Java User’s Guide

4 / 35

It allows an XML comparison to be made that ignores differences in the values of text and attribute nodes, for example when comparing a skeleton or outline piece of XML to some generated XML.

The following test illustrates the use of a custom DifferenceListener:

Example 1.6 Using a custom DifferenceListener

public void testCompareToSkeletonXML() throws Exception {

String myControlXML = "<location><street-address>22 any street</street-address>< -

postcode>XY00 99Z</postcode></location>";

String myTestXML = "<location><street-address>20 east cheap</street-address><postcode> -

EC3M 1EB</postcode></location>";

 

DifferenceListener myDifferenceListener = new

-

IgnoreTextAndAttributeValuesDifferenceListener(); Diff myDiff = new Diff(myControlXML, myTestXML); myDiff.overrideDifferenceListener(myDifferenceListener); assertTrue("test XML matches control skeleton XML",

myDiff.similar());

}

The DifferenceEngine class generates the events that are passed to a DifferenceListener implementation as two pieces of XML are compared. Using recursion it navigates through the nodes in the control XML DOM, and determines which node in the test XML DOM qualifies for comparison to the current control node. The qualifying test node will match the control node’s node type, as well as the node name and namespace (if defined for the control node).

However when the control node is an Element, it is less straightforward to determine which test Element qualifies for comparison as the parent node may contain repeated child Elements with the same name and namespace. So for Element nodes, an instance of the ElementQualifier interface is used determine whether a given test Element node qualifies for comparison with a control Element node. This separates the decision about whether two Elements should be compared from the decision about whether those two Elements are considered similar. By default an ElementNameQualifier class is used that compares the nth child <abc> test element to the nth child <abc> control element, i.e. the sequence of the child elements in the test XML is important. However this default behaviour can be overridden using an ElementNameAndTextQ ualifier or ElementNameAndAttributesQualifier.

The test below demonstrates the use of a custom ElementQualifier:

Example 1.7 Using a custom ElementQualifier

 

public void testRepeatedChildElements() throws Exception {

 

 

 

String myControlXML = "<suite>"

 

 

 

+ "<test status=\"pass\">FirstTestCase</test>"

 

 

 

+ "<test status=\"pass\">SecondTestCase</test></suite>";

 

 

 

String myTestXML = "<suite>"

 

 

 

+ "<test status=\"pass\">SecondTestCase</test>"

 

 

 

+ "<test status=\"pass\">FirstTestCase</test></suite>";

 

 

 

assertXMLNotEqual("Repeated child elements in different sequence order are not equal by

-

 

 

default",

 

 

 

myControlXML, myTestXML);

 

 

 

Diff myDiff = new Diff(myControlXML, myTestXML);

 

 

 

myDiff.overrideElementQualifier(new ElementNameAndTextQualifier());

 

 

 

assertXMLEqual("But they are equal when an ElementQualifier controls which test element

-

 

 

is compared with each control element",

 

 

 

myDiff, true);

 

 

 

}

 

 

 

 

 

 

 

 

 

 

1.6Comparing XML Transformations

XMLUnit can test XSLT transformations at a high level using the Transform class that wraps an javax.xml.transform. Transformer instance. Knowing the input XML, input stylesheet and expected output XML we can assert that the output of the transformation matches the expected output as follows:



XMLUnit Java User’s Guide

5 / 35

Example 1.8 Testing the Result of a Transformation

public void testXSLTransformation() throws Exception { String myInputXML = "...";

File myStylesheetFile = new File("...");

Transform myTransform = new Transform(myInputXML, myStylesheetFile); String myExpectedOutputXML = "...";

Diff myDiff = new Diff(myExpectedOutputXML, myTransform); assertTrue("XSL transformation worked as expected", myDiff.similar());

}

The getResultString() and getResultDocument() methods of the Transform class can be used to access the result of the XSLT transformation programmatically if required, for example as below:

Example 1.9 Using Transform programmatically

public void testAnotherXSLTransformation() throws Exception { File myInputXMLFile = new File("...");

File myStylesheetFile = new File("..."); Transform myTransform = new Transform(

new StreamSource(myInputXMLFile), new StreamSource(myStylesheetFile));

Document myExpectedOutputXML = XMLUnit.buildDocument(XMLUnit.getControlParser(),

new FileReader("...")); Diff myDiff = new Diff(myExpectedOutputXML, myTransform.getResultDocument());

assertTrue("XSL transformation worked as expected", myDiff.similar());

}

1.7Validation Tests

XML parsers that validate a piece of XML against a DTD are common, however they rely on a DTD reference being present in the XML, and they can only validate against a single DTD. When writing a system that exchanges XML messages with third parties there are times when you would like to validate the XML against a DTD that is not available to the recipient of the message and so cannot be referenced in the message itself. XMLUnit provides a Validator class for this purpose.

Example 1.10 Validating Against a DTD

public void testValidation() throws Exception { XMLUnit.getTestDocumentBuilderFactory().setValidating(true);

// As the document is parsed it is validated against its referenced DTD Document myTestDocument = XMLUnit.buildTestDocument("...");

String mySystemId = "...";

String myDTDUrl = new File("...").toURL().toExternalForm(); Validator myValidator = new Validator(myTestDocument, mySystemId,

myDTDUrl); assertTrue("test document validates against unreferenced DTD",

myValidator.isValid());

}

Starting with XMLUnit 1.1, the Validator class can also validate against one or more XML Schema definitions. See Section 4.1.2 for details.

XMLUnit 1.2 introduces a new Validator class that relies on JAXP 1.3’s javax.xml.validation package. This Validator can validate against W3C XML Schema, but may support different Schema languages like RELAX NG if your JAXP implementation supports it. See Section 4.4 for details.