Link to home
Start Free TrialLog in
Avatar of rifaquat
rifaquatFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Unit Testing A Java Method

Hi all,

I have a method which produces XML file from a CSV file. I want to unit test this function. Can you please give me some example code.


public static void CSVTOXML(String inputFile,String outputFileName, char dataDelimiter) throws Exception{
		 	
		    CSVReader reader = new CSVReader(new FileReader(inputFile),dataDelimiter);
		    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		    DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
		    domFactory.setIgnoringElementContentWhitespace(true);
		    Document newDoc = domBuilder.newDocument();
		    String[] currentLine = null;
  	        String[] header = reader.readNext();
            Element rootElement = newDoc.createElement("CSV2XML");
	        newDoc.appendChild(rootElement);

	        while((currentLine = reader.readNext())!=null){

                Element rowElement = newDoc.createElement("row");
                        
                for (int i = 0; i < header.length; i++) {
                	  String curValue = String.valueOf(currentLine[i]);
                      Element curElement = newDoc.createElement(header[i]);
                      curElement.appendChild(newDoc.createTextNode(curValue));
                      rowElement.appendChild(curElement);
                	
                }
                rootElement.appendChild(rowElement);
                 
	        }
	        
	        TransformerFactory tranFactory = TransformerFactory.newInstance();
	        Transformer aTransformer = tranFactory.newTransformer();
	        aTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
            Source src = new DOMSource(newDoc);
            Result dest = new StreamResult(new File("C:\\test.xml").toURI().getPath());
            aTransformer.transform(src, dest);
	      
	        
 
 }

Open in new window

Avatar of brain_box
brain_box

Create a simple simple csv file and its corresponding xml file manually. Compare the generated and manually written file.You may have to ignore spaces and newline.
Avatar of rifaquat

ASKER

comparing two files won't require a call to that funciton isnit. I need to call this function in the unit test to check the integrity and the results.
I think brain_box was suggesting that you create both the input (CSV) and expected output (XML) by hand, then call your function during the unit test, comparing the output of your function with the XML file you generated.

You could also define the input and expected output as constant Strings in your test class, then create a temp file (File.createTempFile(...)) , using that file as the output file for your method.  Read the contents of the file into a String after the method executes, check that EXPECTED.equals(generated) and delete the temp file.
Sorry, missed that the method needed an input file, not a string.  You'll have to create a test input file as well.  Some sample code below:
public class UnitTest {
    private static final String INPUT_CSV = ""; // define input
    private static final String EXPECTED_XML = ""; // define output

    public void testCSVToXML() {
        File inputFile = File.createTempFile("unittestinput", ".csv");
        try {
            FileWriter fw = new FileWriter(inputFile);
            fw.write(INPUT_CSV);
            fw.close();
        } catch (IOException ioe) {
            // unable to write input file, cannot run test
            // either skip test and output warning or fail
        }
        File outputFile = File.createTempFile("unittestoutput", ".xml");
        CSVTOXML(inputFile.getAbsolutePath(), outputFile.getAbsolutePath(), ',');

        StringBuilder output = new StringBuilder();

        try {
            BufferedReader br = new BufferedReader(new FileReader(outputFile));
            String nextLine;
            while ((nextLine = br.readLine()) != null)
                output.append(nextLine).append('\n');
            br.close();
        } catch (IOException ioe) {
            // error reading output file, test failure
        }

        if (!EXPECTED_XML.equals(output.toString()))
            fail("Output not as expected.");
    }
}

Open in new window

Oh, forgot to add these calls to make sure the system cleans up your temp files.  You should call them right after the call to the corresponding File.createTempFile() methods to ensure they are deleted even if exceptions are thrown.

inputFile.deleteOnExit();
outputFile.deleteOnExit();

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of brain_box
brain_box

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Dhaest,

I'd recommend splitting points 70/30 between my post 35243407 and brain_box's post 35243223.
I recommend splitting points between my post http:#35243407 (300) and brain_box's post http:#35243223 (200).
Avatar of modus_operandi
Starting auto-close process to implement the recommendations of the participating Expert(s).
 
modus_operandi
EE Admin