但是以下代码怎么办:
public ClassLoaderProductDataProvider(ClassLoader classLoader, String tocResourcePath, boolean checkTocModifications) {
// ...
this.cl = classLoader;
tocUrl = cl.getResource(tocResourcePath);
if (tocUrl == null) {
throw new IllegalArgumentException("Can' find table of contents file " + tocResourcePath);
}
this.checkTocModifications = checkTocModifications;
toc = loadToc();
// ...
}
private ReadonlyTableOfContents loadToc() {
InputStream is = null;
Document doc;
try {
is = tocUrl.openStream();
doc = getDocumentBuilder().parse(is);
} catch (Exception e) {
throw new RuntimeException("Error loading table of contents from " + tocUrl.getFile(), e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
try {
Element tocElement = doc.getDocumentElement();
ReadonlyTableOfContents toc = new ReadonlyTableOfContents();
toc.initFromXml(tocElement);
return toc;
} catch (Exception e) {
throw new RuntimeException("Error creating toc from xml.", e);
}
}
这个类会通过位于tocResource的文件的内容来初始化它的toc属性。
因此,对于测试,我首先想到的是创建一个子类,在构造函数中不调用super,这样所有的文件访问都不会执行。然后在我的构造函数中,我插入了应该从文件中读取的测试虚拟数据。这样我就可以毫无问题地测试类的其余部分。
然而,原始类的构造函数代码根本没有被测试过。如果出现错误怎么办?