ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 02.01.2026
Просмотров: 487
Скачиваний: 0
XMLUnit Java User’s Guide |
10 / 35 |
2.3Using XMLUnit With JUnit 3.x
Initially XMLUnit was tightly coupled to JUnit and the recommended approach was to write unit tests by inheriting from the XMLTestCase class. XMLTestCase provides a pretty long list of assert... methods that may simplify your interaction with XMLUnit’s internals in many common cases.
The XMLAssert class provides the same set of assert...s as static methods. Use XMLAssert instead of XMLTestCase for your unit tests if you can’t or don’t want to inherit from XMLTestCase.
All power of XMLUnit is available whether you use XMLTestCase and/or XMLAssert or the underlying API directly. If you are using JUnit 3.x then using the specific classes may prove to be more convenient.
2.4Common Configuration Options
2.4.1JAXP
If you are using a JDK 1.4 or later, your Java class library already contains the required XML parsers and XSLT transformers. Still you may want to use a different parser/transformer than the one of your JDK - in particular since the versions shipping with some JDKs are known to contain serious bugs.
As described in Section 1.4 there are two main approaches to choose the XML parser of XSLT transformer: System properties and setters in the XMLUnit class.
If you use system properties you have the advantage that your choice affects the whole JAXP system, whether it is used inside of XMLUnit or not. If you are using JDK 1.4 or later you may also want to review the Endorsed Standards Override Mechanism to use a different parser/transformer than the one shipping with your JDK.
The second option - using the XMLUnit class - allows you to use different parsers for control and test documents, it even allows you to use different parsers for different test cases, if you really want to stretch it that far. It may also work for JDK 1.4 and above, even if you don’t override the endorsed standards libraries.
You can access the underlying JAXP parser by XMLUnit.newControlParser, XMLUnit.newTestParser, XMLUnit. getControlDocumentBuilderFactory, XMLUnit.getTestDocumentBuilderFactory and XMLUnit.getS AXParserFactory (used by Validator). Note that all these methods return factories or parsers that are namespace aware.
The various build... methods in XMLUnit provide convenience layers for building DOM Documents using the configured parsers.
You can also set the class name for the XPathFactory to use when using JAXP 1.3 by passing the class name to XMLUnit. setXPathFactory.
2.4.2 EntityResolver
You can provide a custom org.xml.sax.EntityResolver for the control and test parsers via XMLUnit.setControl EntityResolver and XMLUnit.setTestEntityResolver. Validator uses the resolver set via setControlEn tityResolver as well.
2.4.3Element Content Whitespace
Element content whitespace - also known as ignorable whitespace - is whitespace contained in elements whose content model doesn’t allow text content. I.e. the newline and space characters between <foo> and <bar> in the following example could belong into this category.
<foo>
<bar/></foo>
Using XMLUnit.setIgnoreWhitespace it is possible to make the test and control parser ignore this kind of whitespace.
Note that setting this property to true usually doesn’t have any effect since it only works on validating parsers and XMLUnit doesn’t enable validation by default. It does have an effect when comparing pieces of XML, though, since the same flag is used for a different purpose as well in that case. See Section 3.8.1 for more details.
XMLUnit Java User’s Guide |
11 / 35 |
2.4.4XSLT Stylesheet Version
Some features of XMLUnit use XSLT stylesheets under the covers, in particular XSLT will be used to strip element content whitespace or comments as well as by SimpleXpathEngine. These stylesheets only require a XSLT transformer that supports XSLT 1.0 and will say so in the stylesheet element.
If your XSLT transformer supports XSLT 2.0 or newer it may6 issue a warning for these stylesheets which can be annoying. You can use XMLUnit.setXSLTVersion to make XMLUnit change the version attribute to a different value. Note that XMLUnit hasn’t been tested with a value other than "1.0".
2.5Providing Input to XMLUnit
Most methods in XMLUnit that expect a piece of XML as input provide several overloads that obtain their input from different sources. The most common options are:
•A DOM Document.
Here you have all control over the document’s creation. Such a Document could as well be the result of an XSLT transformation via the Transform class.
•A SAX InputSource.
This is the most generic way since InputSource allows you to read from arbitrary InputStreams or Readers. Use an InputStream wrapped by an InputSource if you want the XML parser to pick up the proper encoding from the XML declaration.
•A String.
Here a DOM Document is built from the input String using the JAXP parser specified for control or test documents - depending on whether the input is a control or test piece of XML.
Note that using a String assumes that your XML has already been converted from its XML encoding to a Java String upfront.
•A Reader.
Here a DOM Document is built from the input Reader using the JAXP parser specified for control or test documents - depending on whether the input is a control or test piece of XML.
Note that using a Reader is a bad choice if your XML encoding is different from your platform’s default encoding since Java’s IO system won’t read your XML declaration. It is a good practice to use one of the other overloads rather than the Reader version to ensure encoding has been dealt with properly.
3 Comparing Pieces of XML
3.1The Difference Engine
At the center of XMLUnit’s support for comparisons is the DifferenceEngine class. In practice you rarely deal with it directly but rather use it via instances of Diff or DetailedDiff classes (see Section 3.5).
The DifferenceEngine walks two trees of DOM Nodes, the control and the test tree, and compares the nodes. Whenever it detects a difference, it sends a message to a configured DifferenceListener (see Section 3.3) and asks a ComparisonC ontroller (see Section 3.2) whether the current comparison should be halted.
In some cases the order of elements in two pieces of XML may not be significant. If this is true, the DifferenceEngine needs help to determine which Elements to compare. This is the job of an ElementQualifier (see Section 3.4).
The types of differences DifferenceEngine can detect are enumerated in the DifferenceConstants interface and represented by instances of the Difference class.
6 The W3C recommendation says it SHOULD.
XMLUnit Java User’s Guide |
12 / 35 |
A Difference can be recoverable; recoverable Differences make the Diff class consider two pieces of XML similar while non-recoverable Differences render the two pieces different.
The types of Differences that are currently detected are listed in Table 1 to Table 4 (the first two columns refer to the
DifferenceConstants class).
Note that some of the differences listed may be ignored by the DifferenceEngine if certain configuration options have been specified. See Section 3.8 for details.
DifferenceEngine passes differences found around as instances of the Difference class. In addition to the type of of difference this class also holds information on the nodes that have been found to be different. The nodes are described by NodeDetail instances that encapsulate the DOM Node instance as well as the XPath expression that locates the Node inside the given piece of XML. NodeDetail also contains a "value" that provides more information on the actual values that have been found to be different, the concrete interpretation depends on the type of difference as can be seen in Table 5.
As said in the first paragraph you won’t deal with DifferenceEngine directly in most cases. In cases where Diff or DetailedDiff don’t provide what you need you’d create an instance of DifferenceEngine passing a ComparisonCo ntroller in the constructor and invoke compare with your DOM trees to compare as well as a DifferenceListener and ElementQualifier. The listener will be called on any differences while the control method is executing.
Example 3.1 Using DifferenceEngine Directly
class MyDifferenceListener implements DifferenceListener { private boolean calledFlag = false;
public boolean called() { return calledFlag; }
public int differenceFound(Difference difference) { calledFlag = true;
return RETURN_ACCEPT_DIFFERENCE;
}
public void skippedComparison(Node control, Node test) {
}
}
DifferenceEngine engine = new DifferenceEngine(myComparisonController); MyDifferenceListener listener = new MyDifferenceListener(); engine.compare(controlNode, testNode, listener,
myElementQualifier); System.err.println("There have been "
+(listener.called() ? "" : "no ")
+"differences.");
3.2ComparisonController
The ComparisonController’s job is to decide whether a comparison should be halted after a difference has been found. Its interface is:
/**
*Determine whether a Difference that the listener has been notified of
*should halt further XML comparison. Default behaviour for a Diff
*instance is to halt if the Difference is not recoverable.
*@see Difference#isRecoverable
*@param afterDifference the last Difference passed to <code>differenceFound</code>
*@return true to halt further comparison, false otherwise
*/
boolean haltComparison(Difference afterDifference);
7 Note that the order of attributes is not significant in XML, different parsers may return attributes in a different order even if parsing the same XML document. There is an option to turn this check off - see Section 3.8 - but it is on by default for backwards compatibility reasons
8 In order for this difference to be detected the parser must have been in validating mode when the piece of XML was parsed and the DTD or XML Schema must have been available.
XMLUnit Java User’s Guide |
13 / 35 |
ID |
Constant |
recoverable |
Description |
|
HAS_DOCTYPE_DECLAR |
HAS_DOCTYPE_DECLAR |
|
One piece of XML has a |
|
true |
DOCTYPE declaration |
|||
ATION_ID |
ATION |
|||
|
while the other one has not. |
|||
|
|
|
||
|
|
|
Both pieces of XML |
|
|
|
|
contain a DOCTYPE |
|
DOCTYPE_NAME_ID |
DOCTYPE_NAME |
false |
declaration but the |
|
declarations specify |
||||
|
|
|
||
|
|
|
different names for the root |
|
|
|
|
element. |
|
|
|
|
Both pieces of XML |
|
|
|
|
contain a DOCTYPE |
|
DOCTYPE_PUBLIC_ID |
DOCTYPE_PUBLIC_ID |
false |
declaration but the |
|
_ID |
declarations specify |
|||
|
|
|||
|
|
|
different PUBLIC |
|
|
|
|
identifiers. |
|
|
|
|
Both pieces of XML |
|
|
|
|
contain a DOCTYPE |
|
DOCTYPE_SYSTEM_ID |
DOCTYPE_SYSTEM_ID |
true |
declaration but the |
|
_ID |
declarations specify |
|||
|
|
|||
|
|
|
different SYSTEM |
|
|
|
|
identifiers. |
|
|
|
|
The test piece of XML |
|
|
|
|
contains a different type of |
|
|
|
|
node than was expected. |
|
NODE_TYPE_ID |
NODE_TYPE |
false |
This type of difference will |
|
|
|
|
also occur if either the root |
|
|
|
|
control or test Node is |
|
|
|
|
null while the other is not. |
|
|
|
|
Two nodes use different |
|
NAMESPACE_PREFIX |
NAMESPACE_PREFIX |
true |
prefixes for the same XML |
|
_ID |
Namespace URI in the two |
|||
|
|
|||
|
|
|
pieces of XML. |
|
|
|
|
Two nodes in the two pieces |
|
NAMESPACE_URI_ID |
NAMESPACE_URI |
false |
of XML share the same |
|
local name but use different |
||||
|
|
|
||
|
|
|
XML Namespace URIs. |
|
|
|
|
Two nodes have different |
|
|
|
|
values for the |
|
|
|
|
schemaLocation |
|
SCHEMA_LOCATION_ID |
SCHEMA_LOCATION |
true |
attribute of the |
|
XMLSchema-Instance |
||||
|
|
|
||
|
|
|
namespace. The attribute |
|
|
|
|
could be present on only |
|
|
|
|
one of the two nodes. |
|
|
|
|
Two nodes have different |
|
|
|
|
values for the noNamespa |
|
|
|
|
ceSchemaLocation |
|
NO_NAMESPACE_SCHEM |
NO_NAMESPACE_SCHEM |
true |
attribute of the |
|
A_LOCATION_ID |
A_LOCATION |
XMLSchema-Instance |
||
|
||||
|
|
|
namespace. The attribute |
|
|
|
|
could be present on only |
|
|
|
|
one of the two nodes. |
Table 1: Document level Differences detected by DifferenceEngine