简体   繁体   English

Java Mockito-在DocumentBuilder.parse期间无法引发IOException

[英]Java Mockito - Unable to throw IOException during DocumentBuilder.parse

I am trying to create a JUnit test to fire IOException during DocumentBuilder.parse(InputSource.class). 我正在尝试创建一个JUnit测试,以在DocumentBuilder.parse(InputSource.class)期间触发IOException。

I not sure why my "doThrow" method is not firing IOException. 我不确定为什么我的“ doThrow”方法没有触发IOException。

The source code is as below: JUnit class: 源代码如下:JUnit类:

@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;
    }

You should use: 您应该使用:

doThrow(IOException.class)

Instead of instantiating it. 而不是实例化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM