【发布时间】: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