How to run junit tests on a method that returns void?

I cannot change the signature of the method that needs to be tested. The test code looks like below

Parser test = new Parser(props);
ArrayList<HDocument> list = new ArrayList<HDocument>();

test.parse("/users/mac/test.xml", list);
System.out.println("Size of list: "+list.size());
assertEquals(5, list.size());

parse method signature is as below

public void parse(String filename, Collection<HDocument> docs)

The parse method runs fine, but when I run the tester, the list size is always 0. I cannot change the parse method signature. How should I do it?

Here is the Parser class,

class Parser{
private Collection<HDocument> docs;
     public void parse(String filename, Collection<HDocument> docs) {
        docs = new ArrayList<HDocument>();
        Collection<HDocument> docsFromXml = new ArrayList<HDocument>();

            Handler hl = new Handler();
            try {
                docsFromXml = hl.getDocs(filename);
            } catch (Exception e) {
                e.printStackTrace();
            }
            docs = docsFromXml;
            System.out.println("Size:"
                    + docs.size()); // This prints the size correctly

        }
    }

}

Answer

If parse is supposed to add the results into the docs collection, and the size of docs is zero after you run the parse method, then your test is telling you that parse is broken, or you’re calling it wrong. That’s what tests are supposed to do: tell you that something isn’t working.

In short: you’re testing parse correctly, and your test is correctly telling you something else is broken. Your test is fine; it’s parse that must be wrong somehow. (Perhaps the question you should be asking StackOverflow is how to fix your parse method.)

Leave a Reply

Your email address will not be published. Required fields are marked *