Skip to content

Provide methods to unambiguously send form data with MockMvc #32757

Closed
@wilkinsona

Description

@wilkinsona

A recent Spring REST Docs issue has reminded me of the ambiguity of using the param method when building a mock request. You cannot tell if the parameter was intended to come from the request's query string or its body which causes REST Docs some problems as it has to guess. Beyond REST Docs, even when setting the content type to indicate that parameters (probably) come from the body, a test like this will fail:

@Test
void formUrlEncodedRequestBuiltWithParam() throws Exception {
	MockHttpServletRequest mockRequest = MockMvcRequestBuilders.patch("/foo")
			.contentType(MediaType.APPLICATION_FORM_URLENCODED).param("a", "alpha")
			.param("b", "bravo").buildRequest(new MockServletContext());
	assertThat(mockRequest.getContentLength()).isGreaterThan(0);
	assertThat(mockRequest.getContentAsString()).isNotEmpty();
}

I discussed this many years ago with @rstoyanchev where he suggested that some new methods specifically for adding form parameters could be introduced. I would welcome such an addition, ideally alongside the deprecation of the param method, as it would allow test code to unambiguously describe the request. This would benefit REST Docs and would also, I believe, allow MockMvc to automatically populate the request's body from the form parameters which, as shown by the test above, it does not do today.

Metadata

Metadata

Assignees

Labels

in: 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