Skip to content

Commit

Permalink
XpathResultMatcher supports Hamcrest Matcher NodeList
Browse files Browse the repository at this point in the history
Use when xpath result is XPathConstants.NODESET
  • Loading branch information
Pat Turner committed Nov 22, 2018
1 parent 548126d commit 1ec4463
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
Expand Up @@ -40,6 +40,8 @@
import org.springframework.util.StringUtils;
import org.springframework.util.xml.SimpleNamespaceContext;

import static org.hamcrest.MatcherAssert.*;


/**
* A helper class for applying assertions via XPath expressions.
Expand Down Expand Up @@ -102,6 +104,18 @@ public void assertNode(byte[] content, @Nullable String encoding, final Matcher<
MatcherAssert.assertThat("XPath " + this.expression, node, matcher);
}

/**
* Parse the content, evaluate the XPath expression as a {@link NodeList},
* and assert it with the given {@code Matcher<NodeList>}.
*/
public void assertNodeList(byte[] content, @Nullable String encoding, final Matcher<? super NodeList> matcher)
throws Exception {

Document document = parseXmlByteArray(content, encoding);
NodeList nodeList = evaluateXpath(document, XPathConstants.NODESET, NodeList.class);
assertThat("XPath " + this.getXpathExpression(), nodeList, matcher);
}

/**
* Apply the XPath expression and assert the resulting content exists.
* @throws Exception if content parsing or expression evaluation fails
Expand Down
Expand Up @@ -21,6 +21,7 @@

import org.hamcrest.Matcher;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.springframework.lang.Nullable;
import org.springframework.mock.web.MockHttpServletResponse;
Expand Down Expand Up @@ -68,6 +69,17 @@ public ResultMatcher node(final Matcher<? super Node> matcher) {
};
}

/**
* Evaluate the XPath and assert the {@link NodeList} content found with the
* given Hamcrest {@link Matcher}.
*/
public ResultMatcher nodeList(final Matcher<? super NodeList> matcher) {
return result -> {
MockHttpServletResponse response = result.getResponse();
this.xpathHelper.assertNodeList(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
};
}

/**
* Get the response encoding if explicitly defined in the response, {code null} otherwise.
*/
Expand Down
Expand Up @@ -45,6 +45,16 @@ public void nodeNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar", null).node(Matchers.nullValue()).match(getStubMvcResult());
}

@Test
public void nodeList() throws Exception {
new XpathResultMatchers("/foo/bar", null).nodeList(Matchers.notNullValue()).match(getStubMvcResult());
}

@Test(expected = AssertionError.class)
public void nodeListNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar", null).nodeList(Matchers.nullValue()).match(getStubMvcResult());
}

@Test
public void exists() throws Exception {
new XpathResultMatchers("/foo/bar", null).exists().match(getStubMvcResult());
Expand Down

0 comments on commit 1ec4463

Please sign in to comment.