Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XpathResultMatcher supports Hamcrest Matcher NodeList #2023

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -102,6 +102,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);
MatcherAssert.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