Add params(MultiValueMap) to MockMvc

Issue: SPR-13801
This commit is contained in:
Rossen Stoyanchev 2015-12-16 11:51:59 -05:00
parent 5626384812
commit c8aa48faa9
2 changed files with 32 additions and 0 deletions

View File

@ -151,6 +151,21 @@ public class MockHttpServletRequestBuilder
return this; return this;
} }
/**
* Add request parameters to the {@link MockHttpServletRequest} for example
* such as when testing a form submission. If called more than once, the new
* values are added.
* @param params the parameters to add
*/
public MockHttpServletRequestBuilder params(MultiValueMap<String, String> params) {
for (String name : params.keySet()) {
for (String value : params.get(name)) {
this.parameters.add(name, value);
}
}
return this;
}
/** /**
* Add a header to the request. Values are always added. * Add a header to the request. Values are always added.
* @param name the header name * @param name the header name

View File

@ -39,6 +39,8 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockServletContext; import org.springframework.mock.web.MockServletContext;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.servlet.FlashMap; import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.support.SessionFlashMapManager; import org.springframework.web.servlet.support.SessionFlashMapManager;
@ -252,6 +254,21 @@ public class MockHttpServletRequestBuilderTests {
assertEquals("foo", request.getQueryString()); assertEquals("foo", request.getQueryString());
} }
// SPR-13801
@Test
public void requestParameterFromMultiValueMap() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("foo", "bar");
params.add("foo", "baz");
this.builder = new MockHttpServletRequestBuilder(HttpMethod.POST, "/foo");
this.builder.params(params);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertArrayEquals(new String[] {"bar", "baz"}, request.getParameterMap().get("foo"));
}
@Test @Test
public void acceptHeader() { public void acceptHeader() {
this.builder.accept(MediaType.TEXT_HTML, MediaType.APPLICATION_XML); this.builder.accept(MediaType.TEXT_HTML, MediaType.APPLICATION_XML);