【发布时间】:2021-03-16 23:00:57
【问题描述】:
我有一个接受文件路径并对该文件进行一些处理的方法。但如果路径不正确,我想抛出 FileNotFoundException 并从中创建一个测试。
由于我的方法在其 catch 中引发了另一个名为 FileParsingException 的异常,因此我必须将其添加到 throws 中或尝试在测试方法周围进行 catch。
如果我想为FileNotFoundException 创建一个测试,它不会让我和java.lang.AssertionError: Expected exception: java.io.FileNotFoundException 这样的断言错误出错。我无法删除FileParsingException,所以我该如何添加FileNotFoundException 测试或就此而言可以是什么
这是我的方法的样子:
public <T> Object getSAXSource(File xmlFile, Class<T> clazz) throws FileParsingException {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller um = jaxbContext.createUnmarshaller();
// Disable XXE
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
// Read the contents
InputStream is = new FileInputStream(xmlFile);
InputSource inputSource = new InputSource(is);
Source xmlSource = new SAXSource(xmlReader, inputSource);
return um.unmarshal(xmlSource);
} catch (FileNotFoundException | SAXException | JAXBException e) {
LOGGER.error("XmlParsingUtil:getSAXSource():: Error on while parsing::" + e.getMessage());
throw new FileParsingException(e.getMessage(), e);
}
}
这就是我尝试创建 JUNIT 的方式
//@Test(expected = FileParsingException.class)
@Test(expected = FileNotFoundException.class)
public void testGetSAXSourceFileNotFound() {
File file = new File(resourcePath + "/Invalid.xml");
try {
util.getSAXSource(file, MyXMLClass.class);
Assert.fail("Exception was expected");
} catch (FileParsingException e) {
e.printStackTrace();
}
}
有人可以指导我如何为 catch 块创建联结。此时,任何正在测试的异常都将起作用,因为覆盖率表明 catch 块未被覆盖。
【问题讨论】:
标签: java junit mockito jaxb junit4