8

How would I write a unit test, say JUnit, for validating an XML file?

I have an application that creates a document as an XML file. In order to validate this XML structure, do I need to create an XML mock object and compare each of its elements against the ones in the 'actual' XML file?

IF SO: Then what is the best practice for doing so? e.g. would I use the XML data from the 'actual' XML file to create the mock object? etc.

IF NOT: What is a valid unit test?

gnat
20.5k29 gold badges117 silver badges308 bronze badges
asked Jan 29, 2016 at 23:55
1
  • for starter separate the xml part from the file io part if you can Commented Apr 5, 2016 at 12:38

1 Answer 1

8

To validate an XML file, you first need an XML Schema Definition (XSD) that describes the structure of a valid XML document. You can find the specification for XSD files at W3C.

Going into how to build the XSD requires knowing how your XML should be structured.

For detailed information about the actual Java implementation of this, check out What's the best way to validate an XML file against an XSD file? on StackOverflow.

Relevant code from that post:

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
...
URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
Source xmlFile = new StreamSource(new File("web.xml"));
SchemaFactory schemaFactory = SchemaFactory
 .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
try {
 validator.validate(xmlFile);
 System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
 System.out.println(xmlFile.getSystemId() + " is NOT valid");
 System.out.println("Reason: " + e.getLocalizedMessage());
}
answered Jan 30, 2016 at 0:28
3
  • So validating an XML only means to validate against its schema and not against a mock XML, correct? Commented Jan 30, 2016 at 0:29
  • 1
    You can do either, but I would recommend the validation using the schema. It will be more robust of a comparison than verifying the mock matches what you expect. Commented Jan 30, 2016 at 0:32
  • Beware that xsd can create a hyper rigid schema. Take the time to understand how schema changes will impact you with respect to forwards/backwards compatibility. Commented Jan 30, 2016 at 14:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.