【问题标题】:How to cover IOException from method that has InputStream in JUnit如何从 JUnit 中具有 InputStream 的方法中覆盖 IOException
【发布时间】:2021-01-15 16:56:30
【问题描述】:

想就我的 JUnit 测试寻求帮助。在我的方法中,除了需要抛出 IOException 的部分之外,我能够涵盖所有内容。我已经为此做了很多解决方法,但似乎都没有。

这里是单元测试中没有覆盖IOException的方法

public String GetstrXMLValue(String strXML, String strCriteria) {
    SAXBuilder builder = new SAXBuilder();
    builder.setProperty(XMLConstants.ACCESS_S1, "");
    builder.setProperty(XMLConstants.ACCESS_S2, "");

    Document xmlDocument;
    String strValue = "";
    ErrorHandler objErrHdl = new ErrorHandler();
    
    try {
        InputStream objStream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));

        xmlDocument = builder.build(objStream);
            
        XPathFactory xpath = XPathFactory.instance(); 
      
        XPathExpression<Object> expr = xpath.compile(strCriteria);
      
        List<Object> xPathSearchedNodes = expr.evaluate(xmlDocument);
        
        if (xPathSearchedNodes.size() > 0) {
        
            Content content = (Content) xPathSearchedNodes.get(0);
            
            strValue = content.getValue().toString();
        }
        
    } catch (JDOMException e) {
        objErrHdl.LogError(this.getClass().getName(), "GetstrXMLValue", "ERROR RETRIEVING XML VALUES (XML=" + strXML + ";CRITERIA=" + strCriteria + ")", e.toString());
    } catch (IOException e) {
        objErrHdl.LogError(this.getClass().getName(), "GetstrXMLValue", "ERROR RETRIEVING XML VALUES (XML=" + strXML + ";CRITERIA=" + strCriteria + ")", e.toString());
    } catch (Exception e) {
        objErrHdl.LogError(this.getClass().getName(), "GetstrXMLValue", "ERROR RETRIEVING XML VALUES (XML=" + strXML + ";CRITERIA=" + strCriteria + ")", e.toString());
    }
            
    return strValue;
}

这是我的 JUnit 测试

@Test
public void testGetstrXMLValueThrowsIOException() throws IOException, ParserConfigurationException, SAXException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
    OutputStream responseBody = new ByteArrayOutputStream();
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + 
            "                <RESULT>\r\n" + 
            "                <SHORT_NAME>XXXXXXXXXXXXX</SHORT_NAME>\r\n" + 
            "                <ID_CODE>9999999999999</ID_CODE>\r\n" + 
            "                </RESULT>";
    
    xmlHandler.XMLGenerateRootResult();
    xmlHandler.GetstrXMLValue(xml, ".//RESULT/ID_CODE/text()");
    try
    {
        InputStream input = XMLHandlerTest.readXML(xml);
        byte[] buffer = new byte[1024];
        int bytesRead;
        input.close();
        while ((bytesRead = input.read(buffer)) > 0)
        {
            responseBody.write(buffer, 0, bytesRead);
            
            throw new IOException();
        }
    }
    catch(IOException e)
    {
        System.out.println(e);
    }

}

【问题讨论】:

    标签: java junit mockito inputstream ioexception


    【解决方案1】:

    你的问题不清楚。

    您的意思是:如果发生 IOException,我如何使测试失败

    没有抓住它。测试用例的默认行为,如果它抛出异常,则认为该测试用例失败。请注意,System.out.println(e); 抛出了大量关于错误的有用信息,AND 意味着代码将继续运行。 e.printStackTrace();LOG.something()System.out.println() 如果您在 catch 块中执行此操作,基本上总是错误。别那样做。如果您懒得处理问题或不知道如何处理,catch 块中唯一正确的“我不知道”代码是:

    catch (Whatever e) {
        throw new RuntimeException("uncaught", e);
    }
    

    在这种情况下,只需完全删除 try/catch,如果发生 IOException,您的测试将正常失败。

    你的意思是:如果 IT 抛出 IOException,我需要测试我的方法;如何测试它是否正确?

    嗯,没有意义,是吗?如果发生 IOException,您的方法显然会被破坏,因为您的方法将记录一些内容并继续运行。这很愚蠢,我认为尝试向您解释如何编写单元测试来测试您的方法是否返回任意误导值并写入日志消息对我没有用处。我认为没有人真正想要这种行为。

    让你的方法在出错时抛出一些东西,你可以很容易地用 junit 确认它是这样做的。给它自己的测试方法并注解:

    @Test(expected = IOException.class)
    public void testSomething() {
        if (Boolean.TRUE) throw new IOException();
        // this test will _PASS_, because we said
        // it SHOULD throw IOException.
    }
    

    你的意思是:如何让这个方法抛出 IOException?

    除非您破坏了使之成为可能的方法,否则这并非易事。如果您停止捕获异常并将它们变成愚蠢的事情(一条日志消息并继续执行代码),那么代码覆盖率就不再是问题了。完全摆脱那些 catch 块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多