当相关方法有多个预期异常时如何测试单个异常

问题描述

我有一种方法可以接受文件路径并对该文件进行一些处理。但是如果路径不正确,我想抛出 FileNotFoundException 并从中创建一个测试。

由于我在 catch 中的方法抛出了另一个名为 FileParsingException 的异常,我必须在 throws 或 try 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 块创建junit。此时,任何正在测试的异常都将起作用,因为覆盖率表明未覆盖 catch 块。

解决方法

看来你的想法太复杂了(或者我误解了你想要做什么)。

由于您希望 getSAXSource 方法抛出 FileParsingException, 您使用 @Test(expected = FileParsingException.class) 注释测试方法。 为了让编译器满意,你需要声明方法 与throws FileParsingException。 您不需要 try/catch 和 Assert.fail("Exception was expected") 因为 JUnit 将为您完成所有这些工作。 (即,当没有抛出 FileParsingException 时,测试将失败。 当抛出任何其他异常时,它也会失败。)

所以你最终得到了一个非常简单的测试方法:

@Test(expected = FileParsingException.class)
public void testGetSAXSourceFileNotFound() throws FileParsingException {
    
    File file = new File(resourcePath + "/Invalid.xml");

    util.getSAXSource(file,MyXMLClass.class);
}

可能你需要 3 个不同的测试用例,来测试所有 3 种 异常(FileNotFoundExceptionSAXExceptionJAXBException) 在您的 getSAXSource 方法中处理, 并验证所有这些都导致 FileParsingException