Java Mockito - Unable to throw IOException during DocumentBuilder.parse

假如想象 提交于 2021-02-11 12:32:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!