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();
		    Document newDoc = domBuilder.newDocument();
		    String[] currentLine = null;
  	        String[] header = reader.readNext();
            Element rootElement = newDoc.createElement("CSV2XML");

	        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]);
	        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

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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.
rifaquatAuthor Commented:
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.
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

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);
        } 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)
        } 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.


Open in new window

The code above will need a few more changes:

1. There may be issues with the white space,newline and tabs if you use equals. Basically comparing them as a String will not work. Use line by line String comparison after trimming if not using a push based xml parsing api like stax.
2. If input is multi line, it will be pain to give it as a string.
3. Although not required, you will need to extend TestCase if you want to use junit.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
1.  Very good point.  The comparison between expected and actual output will probably need more effort than a simple .equals().

2.  Multi-line string is definitely a pain but it does avoid missing resource issues.  An alternative would be to include the dummy input file in the same package as the test class, then copy it to the temp file instead of writing the String.  (ClassLoader.openResourceAsStream("com.mypackage.test-input.csv"))

3.  I deliberately left all the JUnit code out and just wrote a simple test, but using a testing framework is a good way to go if you aren't using it already.  If you're using JUnit 4, you don't have to worry about extending TestCase, you can just annotate the test method with @Test.  I'd also move the input/ouput file setup to the class setup/cleanup methods.

public class CsvToXmlTest {
    private File inputFile;
    private File outputFile;

    public static void setUpClass() throws Exception {
        // Load dummy input CSV from file or constant String
        // and copy it into a temp file.

        // initialize temporary output file for use in test

        // You may also want to store the expected output in
        // a resource in the classpath and load it here too.

    public static void tearDownClass() throws Exception {
        // delete all temporary files here

    public void testCsvToXml() {
        // run the CSVTOXML method, then load the resulting
        // output file and compare to the expected hand-created
        // output file -- String.equals() may lead to
        // to false-failures due to whitespace differences so
        // a custom comparison will have to be implemented

Open in new window


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).
Starting auto-close process to implement the recommendations of the participating Expert(s).
EE Admin
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.