Skip to content

Introduce queryParamCount() in MockRestRequestMatchers #34703

Closed
@CToner3223

Description

@CToner3223

Summary

Currently, MockRestServiceServer provides MockRestRequestMatchers.queryParam(String, Matcher) to validate parameter values. However, there is no built-in way to:

  1. Assert the total number of query parameters to prevent extra, unexpected parameters.
  2. Verify that each expected parameter is present with the correct value in a concise way.

Users must currently implement a custom RequestMatcher, adding unnecessary complexity.

Proposed Solution

Introduce a new MockRestRequestMatchers method:

public static RequestMatcher queryParamCount(int expectedCount)
  • Ensures that the total number of query parameters matches expectedCount.
  • Prevents extra, unexpected query parameters from sneaking in.

Example Usage

mockServer.expect(requestTo(startsWith("http://example.com/api")))
    .andExpect(queryParam("param1", "1"))  // Ensures param1 exists with value "1"
    .andExpect(queryParam("param2", "1"))  // Ensures param2 exists with value "1"
    .andExpect(queryParam("param3", "hello world"))  // Ensures param3 exists with value "hello world"
    .andExpect(queryParamCount(3))  // Ensures no extra params exist
    .andRespond(withSuccess());

Workarounds

Currently, users must manually parse the URI's query string inside a custom RequestMatcher, which introduces unnecessary boilerplate. Example:

mockServer.expect(request -> {
    URI uri = request.getURI();
    Map<String, List<String>> params = UriComponentsBuilder.fromUri(uri).build().getQueryParams();
    
    if (params.size() != 3) {
        throw new AssertionError("Expected 3 query parameters, but found " + params.size());
    }
    if (!params.containsKey("param1") || !params.get("param1").contains("1")) {
        throw new AssertionError("Missing or incorrect value for param1.");
    }
    if (!params.containsKey("param2") || !params.get("param2").contains("1")) {
        throw new AssertionError("Missing or incorrect value for param2.");
    }
    if (!params.containsKey("param3") || !params.get("param3").contains("hello world")) {
        throw new AssertionError("Missing or incorrect value for param3.");
    }
}).andRespond(withSuccess());

Benefit

Adding queryParamCount() would:

✅ Improve test readability and maintainability.
✅ Prevent silent failures due to extra or missing parameters.
✅ Reduce boilerplate when asserting both parameter existence and correctness.

Would this be a useful addition to MockRestRequestMatchers?

Metadata

Metadata

Assignees

Labels

in: testIssues in the test modulein: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions