StubConfigXPathEvaluator { public Element getElementByXPath(final String expression, final Document document) { Element element = null; XPath xPath = xPathProvider.getXPath(); try { nameSpaceProvider.setNameSpaceContext(xPath); XPathExpression expr = xPath.compile(expression); Node result = (Node) expr.evaluate(document, XPathConstants.NODE); if (result.getNodeType() == Node.ELEMENT_NODE) { element = (Element) result; } } catch (XPathExpressionException e) { throw new DescriptorCannotBeParsedException("Exception while trying to locate node in the stub configuration file", e); } return element; }  Element getElementByXPath(final String expression, final Document document); NodeList getElementsByXPath(final String expression, final Document document);  }
@Test public void testGetElementByXPathShouldReturnElement() throws XPathExpressionException { String expression = ""; given(xPath.compile(expression)).willReturn(xPathExpression); given(xPathExpression.evaluate(document, XPathConstants.NODE)).willReturn(node); given(node.getNodeType()).willReturn(Node.ELEMENT_NODE); Element actual = underTest.getElementByXPath(expression, document); Assert.assertEquals(actual, node); }
@Test public void testGetElementByXPathWhenResultIsNotElementShouldReturnNull() throws XPathExpressionException { String expression = ""; given(xPath.compile(expression)).willReturn(xPathExpression); given(xPathExpression.evaluate(document, XPathConstants.NODE)).willReturn(node); given(node.getNodeType()).willReturn(Node.COMMENT_NODE); Element actual = underTest.getElementByXPath(expression, document); Assert.assertEquals(actual, null); }
@Test(expectedExceptions = DescriptorCannotBeParsedException.class) public void testGetElementByXPathWhenExpressionIsInvalidShouldThrowException() throws XPathExpressionException { String expression = ""; given(xPath.compile(expression)).willThrow(new XPathExpressionException("exception")); underTest.getElementByXPath(expression, document); }