Skip to content

Conversation

reda-alaoui
Copy link

@reda-alaoui reda-alaoui commented Sep 17, 2025

I have testing components making use of MockHttpServletRequestBuilder. These components should be able to mutate the builder but also to check the builder state (e.g. "what is the http method currently stored by the builder?").

By design, the only way to access MockHttpServletRequestBuilder state is to invoke buildRequest to retrieve a MockHttpServletRequest that will allow to check the state via its getters.
I am fine with that.

But I discovered that invoking buildRequest mutates the value of MockHttpServletRequestBuilder#pathInfo:

if ("".equals(this.pathInfo)) {
if (!requestUri.startsWith(this.contextPath + this.servletPath)) {
throw new IllegalArgumentException(
"Invalid servlet path [" + this.servletPath + "] for request URI [" + requestUri + "]");
}
String extraPath = requestUri.substring(this.contextPath.length() + this.servletPath.length());
this.pathInfo = (StringUtils.hasText(extraPath) ?
UrlPathHelper.defaultInstance.decodeRequestString(request, extraPath) : null);
}

This mutation can break the builder once you try to pass it to MockMvc#perform.
An example of scenario:

  1. Make sure MockMvc has a non null defaultRequestBuilder that will be merged in the consumer's provided MockHttpServletRequestBuilder
  2. Create MockHttpServletRequestBuilder instance foo
  3. Invoke MockHttpServletRequestBuilder#buildRequest on foo (with the injectable ServletContext)
  4. Now invoke MockMvc#perform with foo as argument
  5. You may end up with a 404 not found

TLDR: calling buildRequest twice on the MockHttpServletRequestBuilder is not safe. This pull request fixes this.

@reda-alaoui reda-alaoui force-pushed the mock-mvc-rb-idempotency branch from 775c69d to 9c576be Compare September 17, 2025 09:24
@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Sep 17, 2025
@sbrannen sbrannen added in: test Issues in the test module in: web Issues in web modules (web, webmvc, webflux, websocket) labels Sep 17, 2025
@reda-alaoui reda-alaoui marked this pull request as draft September 17, 2025 19:34
@reda-alaoui reda-alaoui marked this pull request as ready for review September 17, 2025 19:38
@reda-alaoui reda-alaoui marked this pull request as draft September 17, 2025 19:38
@reda-alaoui reda-alaoui force-pushed the mock-mvc-rb-idempotency branch from 4177444 to 3df0eac Compare September 18, 2025 08:56
@reda-alaoui reda-alaoui marked this pull request as ready for review September 18, 2025 08:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
in: test Issues in the test module in: web Issues in web modules (web, webmvc, webflux, websocket) status: waiting-for-triage An issue we've not yet triaged or decided on
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants