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

时间:2019-07-11 10:54:49

标签: java junit mockito

我正在尝试创建一个JUnit测试,以在DocumentBuilder.parse(InputSource.class)期间触发IOException。

我不确定为什么我的“ doThrow”方法没有触发IOException。

源代码如下: 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();
        }
    }
}

主类:

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 个答案:

答案 0 :(得分:-2)

您应该使用:

doThrow(IOException.class)

与其实例化。