0

I have built some code to ingest an XML document and parse through the values but now I'm stuck on testing the method.

What would be the proper way to unit run test on this method? I'm also unsure how to pass an xml document to run.

public class WebServiceTools 
{

static public String getVersionFromWSResponseFromDOM(Document responseDocument) {
        String versionDataAsXML = badData;

        try {           
            responseDocument.normalizeDocument();
            NodeList resultList = responseDocument.getElementsByTagName("ti:VersionResponse");
            Element resultElement = (Element) resultList.item(0);

            if (!badData.equalsIgnoreCase(resultElement.getTextContent())) {
                versionDataAsXML = resultElement.getTextContent().trim();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return versionDataAsXML;
    }
}


package org.examples.tools;

import java.lang.reflect.Method;

public class ReflectApp {

public static void main(String[] args) {

//String parameter
Class[] paramString = new Class[1]; 
paramString[0] = String.class;


try{
        //load the AppTest at runtime
    Class cls = Class.forName("org.examples.tools.WebServiceTools");
    Object obj = cls.newInstance();

    //call the printItString method, pass a String param 
    method = cls.getDeclaredMethod("printItString", paramString);
    method.invoke(obj, new String(" Do I put document here?  "));


}catch(Exception ex){
    ex.printStackTrace();
}

}

package org.examples.tools;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

public class TestGetVersion {

public static void main (String[] args) throws Exception { 

    String fileName = "C:/examples/VersionResponse.xml"; // Set path to file
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new File(fileName));
    // Create do
    String result = WebServiceTools.getVersionFromWSResponseFromDOM(doc); 
    // Treat result

   System.out.print(result);

}
}
user3066155
  • 157
  • 2
  • 2
  • 15
  • What you mean? Don't you know how to create an XML `Document` or a generic tool to test code? – Albert Apr 13 '15 at 14:48
  • Sorry for the confusion, I have a responseXml file that I need to parse through using the above code. I'm not sure how to call method using the xml document as a source. I'm trying to test this in eclipse and getting a little confused. – user3066155 Apr 13 '15 at 15:17

1 Answers1

0

I understand your problem is how to read an XML file into a Document, right?

There are several ways and libraries to read an XML from a file: Java: How to read and write xml files?

For instance:

String fileName = ""; // Set path to file
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File(fileName));

Then, just call your method from a main function or a JUnit test:

public static void main (String[] args) { 
    // Create doc
    String result = WebServiceTools.getVersionFromWSResponseFromDOM(doc); 
    // Treat result
}

UPDATE

REFLECTION

Your cls.getDeclaredMethod("printItString", paramString); is correct, although using such parameter is confusing. At first sight I thought it was a String. I'd preferably use

Method method = cls.getDeclaredMethod("printItString", new Class[] {String.class});

I think this makes it clearer (just my opinion).

To call through reflection is just what you did. Didn't it work?

Object result = method.invoke(obj, new Object[] {"whatever string"});

I assume printString is a method on WebServiceTools class, whose signature is printString(String param)

Unmarshall

First things first: As far as I know, unmarshall is usually used to convert an XML back into an Object (in XML serialization libraries, like XStream or JABX), but I guess you meant convert a Document back to String. Am I right?

If so, one way that works:

Source source = new DOMSource(doc);
StringWriter writer = new StringWriter();
Result result = new StreamResult(writer);

// create a transformer
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer        transformer  = transFactory.newTransformer();

// set some options on the transformer
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

// transform the xml document into a string
transformer.transform(source, result);

String xml = writer.getBuffer().toString();

If this is not what you meant, please clarify.

Community
  • 1
  • 1
Albert
  • 1,156
  • 1
  • 15
  • 27
  • Above code worked great. See code above. How would I add assertion to test values? – user3066155 Apr 13 '15 at 16:01
  • @user3066155, Sorry, but after re-edit I'm completely lost about your question. Did you mean, call using reflection? What is `printItString`? Why two main functions? – Albert Apr 13 '15 at 16:07
  • Yes, call using reflection. One main function is using reflection and the other just calling the method using main. – user3066155 Apr 13 '15 at 18:12
  • It works when using my DOM method, but not for unmarshalling. Getting the following error. javax.xml.bind.UnmarshalException: unexpected element (uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Envelope"). Expected elements are (none) Data Not Found at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:647) – user3066155 Apr 13 '15 at 18:41
  • @user3066155, Can you tell where you get the error in code? It could be my english, but I'm still not sure about what are you trying to do. Correct me if I'm wrong, but as far as I understood, you are attempting to get values of a tag named `VersionResponse`, and you want to test those values. See my update about reflection, although I still don't know what `printItString` method is. – Albert Apr 14 '15 at 08:41