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

使用//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)

最佳答案

查看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。

关于java - 为什么dom4j仅在我的测试环境中才为有效的XPath抛出InvalidXPathException?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38398164/

10-12 01:34