NEO
NEO

Reputation: 2001

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

        }
    }

}

Upvotes: 0

Views: 425

Answers (2)

Christian Kuetbach
Christian Kuetbach

Reputation: 16060

The error is the parse-method itself.

public void parse(String filename, Collection<HDocument> docs) {
    docs = new ArrayList<HDocument>(); /* First problem here: The method should add values to the parameter not to a new List-Instance */
    [...]
    docs = docsFromXml; // second error here. you overwrite the list again.

Should be something like:

public void parse(String filename, Collection<HDocument> docs) {
        if(docs==null) throw new IllegalArgumentException("no list for adding values specified");
        if(filename==null) throw new IllegalArgumentException("no filename specified");
        Handler hl = new Handler();
        try {
            docs.addAll(hl.getDocs(filename));
        } catch (Exception e) {
            throw new RuntimeEception(e); // never sink exception without proper handling
        }

    }
}

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198014

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

Upvotes: 5

Related Questions