问题
I am trying to create a JUnit test to fire IOException during DocumentBuilder.parse(InputSource.class).
I not sure why my "doThrow" method is not firing IOException.
The source code is as below: JUnit class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:META-INF/spring/test.xml" })
@Transactional
public class junitTestClass {
@InjectMocks
TargetClass target;
@Rule
public MockitoRule mockito = MockitoJUnit.rule();
@Mock
DocumentBuilder documentBuilder;
@Mock
DocumentBuilderFactory documentBuilderFactory;
@Mock
XPath xpath;
@Test
public void test01() throws InterruptedException, SAXException, IOException, ParserConfigurationException{
when(documentBuilderFactory.newDocumentBuilder()).thenReturn(documentBuilder);
doThrow(new IOException()).when(documentBuilder).parse(any(InputSource.class));
String xml = "<?xml version="1.0" encoding="UTF-8"?><aaa><bbb>123</bbb></aaa>";
String pattern = "//aaa/bbb";
try {
target.parseXML(xml, pattern);
}catch(Exception e) {
e.printStackTrace();
}
}
}
Main Class:
private String parseXML(String xml, String pattern) {
String itemValue ;
try {
DocumentBuilderFactory dFac = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dFac.newDocumentBuilder();
Document document = db.parse(new InputSource(new StringReader(xml)));
XPath xPath = XPathFactory.newInstance().newXPath();
Node msgId = (Node) xPath.compile(pattern).evaluate(document, XPathConstants.NODE);
itemValue = msgId.getTextContent();
} catch (XPathExpressionException | SAXException | ParserConfigurationException | IOException e) {
e.printStackTrace();
}
return itemValue;
}
回答1:
You should use:
doThrow(IOException.class)
Instead of instantiating it.
来源:https://stackoverflow.com/questions/56987610/java-mockito-unable-to-throw-ioexception-during-documentbuilder-parse