繁体   English   中英

如何在返回void的方法上运行junit测试?

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

我无法更改需要测试的方法的签名 测试代码如下所示

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方法签名如下

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

解析方法运行良好,但是当我运行测试仪时,列表大小始终为0。我无法更改解析方法签名。 我该怎么办?

这是解析器类,

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

        }
    }

}

如果应该使用parse将结果添加到docs集合中,并且在运行parse方法之后docs的大小为零,则您的测试将告诉您该parse已损坏,或者您将其称为错误。 那就是测试应该做的:告诉您某些事情不起作用。

简而言之:您正在测试parse正确,并且您的测试正确地告诉您其他错误。 您的测试还不错; parse肯定某种程度上是错误的。 (也许您应该问StackOverflow的问题是如何解决您的parse方法。)

错误是解析方法本身。

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.

应该是这样的:

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
        }

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM