为什么dom4j仅在我的测试环境中为有效的XPath抛出InvalidXPathException?

时间:2016-07-15 14:06:18

标签: java xpath easymock dom4j

我正致力于为一些我在系统中工作的代码编写单元测试,但我遇到了InvalidXPathException被抛出的问题在有效的XPath上。

使用//external|//inline从DOM4J文档中提取出某些元素,它可以在生产中使用,但不能在我的测试环境中使用。不应该是一个问题,因为它是我在环境之外测试的有效XPath。

任何帮助将不胜感激!

jUnit / Easymock测试:

@Test
public void testgetDCR_success(){ 
    RequestContext context = EasyMock.createMock(RequestContext.class);
    FileDal dal = EasyMock.createMock(FileDal.class);
    String xmlContent = "<xml>your sample stuff</xml>";
    Document sampleDoc = Dom4jUtils.newDocument(xmlContent);

    InputStream stream = null;
    try {
        stream = new ByteArrayInputStream(xmlContent.getBytes("UTF-8"));
    } catch(IOException e) {
        Assert.fail("Could not open file stream for test.");
    }

    EasyMock.expect(context.getFileDal()).andReturn(dal).anyTimes();
    EasyMock.expect(dal.getRoot()).andReturn("").anyTimes();
    EasyMock.expect(dal.getSeparator()).andReturn('/').anyTimes();
    EasyMock.expect(dal.exists("/some/path")).andReturn(true);
    EasyMock.expect(dal.read("/some/path")).andReturn(xmlContent);

    EasyMock.expect(dal.getStream("some/path")).andReturn(stream);
    EasyMock.replay(context);
    EasyMock.replay(dal);

    Document doc = new DefaultTransformationService().getDCR(context, "some/path");

    Assert.assertEquals(sampleDoc, doc);
}

导致问题:

@Override
public Document getDCR(RequestContext context, String relativePath) {
    LOGGER.debug(">> getDCR");

    if (StringUtils.isBlank(relativePath)) {
        LOGGER.error("No origin file path given");
        LOGGER.debug("<< getDCR");
        return null;
    }

    Document dcrDoc = null;
    try {
        dcrDoc = ExternalUtils.readXmlFile(context, relativePath);
    }catch (RuntimeException e){
        LOGGER.error("No DCR found at file path: "+relativePath,e);
        LOGGER.debug("<< getDCR");
        return null;
    }

    if (dcrDoc == null) {
        LOGGER.error("Unable to open xml file: " + relativePath);
        LOGGER.debug("<< getDCR");
        return null;
    }
    LOGGER.debug("<< getDCR");

    Set<String> parsedPaths = new HashSet<String>();
    parsedPaths.add(relativePath);

    return parseData(context, dcrDoc, parsedPaths);
}

private Document parseData(RequestContext context, Document dcr, Set<String> parsedPaths) {
    LOGGER.debug(">> parseData");

    // get all nodes that would be converted.
    @SuppressWarnings("unchecked")
    List<Element> elements = dcr.selectNodes("//external|//inline");

    // For each of the nodes present within the document that are of type external or inline
    for (Element element : elements) {
        // process each element in the list of selected elements.
        processElement(context, element, parsedPaths);
    }

    LOGGER.debug("<< parseData");
    return dcr;
}

堆栈追踪:

org.dom4j.InvalidXPathException: Invalid XPath expression:      '//external|//inline'. Caused by: org/jaxen/dom4j/Dom4jXPath
at org.dom4j.xpath.DefaultXPath.parse(DefaultXPath.java:362)
at org.dom4j.xpath.DefaultXPath.<init>(DefaultXPath.java:59)
at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164)
at com.sample.project.service.impl.DefaultTransformationService.parseData(DefaultTransformationService.java:163)
at com.sample.project.service.impl.DefaultTransformationService.getDCR(DefaultTransformationService.java:144)
at com.sample.project.service.impl.DefaultTransformationServiceTest.testgetDCR_success(DefaultTransformationServiceTest.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

1 个答案:

答案 0 :(得分:1)

查看DOM4J源代码,可以看出该异常的根本原因不一定是无效的XPath表达式:

protected static XPath parse(String text) {
    try {
        return new Dom4jXPath(text);
    } catch (JaxenException e) {
        throw new InvalidXPathException(text, e.getMessage());
    } catch (Throwable t) {
        throw new InvalidXPathException(text, t);
    }
}

考虑到消息的外观,可以得出结论Throwable已被捕获。来自InvalidXPathException

public InvalidXPathException(String xpath, Throwable t) {
    super("Invalid XPath expression: '" + xpath 
            + "'. Caused by: " + t.getMessage());
}

不幸的是,在这种情况下,DOM4J隐藏了原始异常,但是

Caused by: org/jaxen/dom4j/Dom4jXPath

表示原始异常是NoClassDefFoundError。

然而,奇怪的是,当明显发现JaxenException时,无法找到Dom4jXPath(因为它们存在于同一个jar(jaxen)中)。无论如何,看起来你的类路径没有正确设置。

顺便说一下,前面的“分析”是基于DOM4J 1.6.1。所以如果你使用另一个版本的YMMV。