Unit testing XML Generation [closed] Unit testing XML Generation [closed] xml xml

Unit testing XML Generation [closed]


First, as pretty much everyone is saying, validate the XML if there's a schema defined for it. (If there's not, define one.)

But you can build tests that are a lot more granular than that by executing XPath queries against the document, e.g.:

string xml="Your xml string here" ;XmlDocument doc = new XmlDocument();doc.LoadXml(xml);path = "/doc/element1[@id='key1']/element2[. = 'value2']";Assert.IsTrue(doc.SelectSingleNode(path) != null);

This lets you test not only whether or not your document is semantically valid, but whether or not the method producing it is populating it with the values that you expect.


Another possibility might be to use XmlReader and check for an error count > 0. Something like this:

    void CheckXml()    {        string _xmlFile = "this.xml";        string _xsdFile = "schema.xsd";         StringCollection _xmlErrors = new StringCollection();        XmlReader reader = null;        XmlReaderSettings settings = new XmlReaderSettings();        settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandler);        settings.ValidationType = ValidationType.Schema;        settings.IgnoreComments = chkIgnoreComments.Checked;        settings.IgnoreProcessingInstructions = chkIgnoreProcessingInstructions.Checked;        settings.IgnoreWhitespace = chkIgnoreWhiteSpace.Checked;        settings.Schemas.Add(null, XmlReader.Create(_xsdFile));        reader = XmlReader.Create(_xmlFile, settings);        while (reader.Read())        {        }        reader.Close();        Assert.AreEqual(_xmlErrors.Count,0);    }        void ValidationEventHandler(object sender, ValidationEventArgs args)    {        _xmlErrors.Add("<" + args.Severity + "> " + args.Message);    }