Introduce queryParamCount() in MockRestRequestMatchers

Closes gh-34703
This commit is contained in:
Sam Brannen
2025-04-03 14:43:23 +02:00
parent 18989123ac
commit d6e35cf1f0
2 changed files with 52 additions and 4 deletions
@@ -19,6 +19,7 @@ package org.springframework.test.web.client.match;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.xpath.XPathExpressionException;
@@ -130,6 +131,7 @@ public abstract class MockRestRequestMatchers {
* @since 5.3.27
* @see #queryParam(String, Matcher...)
* @see #queryParam(String, String...)
* @see #queryParamCount(int)
*/
public static RequestMatcher queryParamList(String name, Matcher<? super List<String>> matcher) {
return request -> {
@@ -158,6 +160,7 @@ public abstract class MockRestRequestMatchers {
* parameter value
* @see #queryParamList(String, Matcher)
* @see #queryParam(String, String...)
* @see #queryParamCount(int)
*/
@SafeVarargs
@SuppressWarnings("NullAway") // Dataflow analysis limitation
@@ -187,6 +190,7 @@ public abstract class MockRestRequestMatchers {
* parameter value
* @see #queryParamList(String, Matcher)
* @see #queryParam(String, Matcher...)
* @see #queryParamCount(int)
*/
@SuppressWarnings("NullAway") // Dataflow analysis limitation
public static RequestMatcher queryParam(String name, String... expectedValues) {
@@ -199,6 +203,25 @@ public abstract class MockRestRequestMatchers {
};
}
/**
* Assert the number of query parameters present in the request.
* @param expectedCount the number of expected query parameters
* @since 7.0
* @see #queryParamList(String, Matcher)
* @see #queryParam(String, Matcher...)
* @see #queryParam(String, String...)
*/
@SuppressWarnings("NullAway") // Dataflow analysis limitation
public static RequestMatcher queryParamCount(int expectedCount) {
return request -> {
Set<String> parameterNames = getQueryParams(request).keySet();
int actualCount = parameterNames.size();
if (expectedCount != actualCount) {
fail("Expected %d query parameter(s) but found %d: %s".formatted(expectedCount, actualCount, parameterNames));
}
};
}
private static MultiValueMap<String, String> getQueryParams(ClientHttpRequest request) {
return UriComponentsBuilder.fromUri(request.getURI()).build().getQueryParams();
}
@@ -359,7 +382,6 @@ public abstract class MockRestRequestMatchers {
private static void assertValueCount(String name, MultiValueMap<String, String> map, int count) {
List<String> values = map.get(name);
String message = "Expected query param <" + name + ">";
if (values == null) {
@@ -371,7 +393,6 @@ public abstract class MockRestRequestMatchers {
}
private static void assertValueCount(String name, HttpHeaders headers, int count) {
List<String> values = headers.get(name);
String message = "Expected header <" + name + ">";
if (values == null) {