Skip to content

Commit

Permalink
Support Servlet Part in Spring MVC Test
Browse files Browse the repository at this point in the history
Issue: SPR-14253
  • Loading branch information
rstoyanchev committed Jan 25, 2017
1 parent c8f98ec commit eabd8a2
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 16 deletions.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -18,14 +18,20 @@

import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.Part;

import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

/**
* Default builder for {@link MockMultipartHttpServletRequest}.
Expand All @@ -38,6 +44,8 @@ public class MockMultipartHttpServletRequestBuilder extends MockHttpServletReque

private final List<MockMultipartFile> files = new ArrayList<>();

private final MultiValueMap<String, Part> parts = new LinkedMultiValueMap<>();


/**
* Package-private constructor. Use static factory methods in
Expand Down Expand Up @@ -87,6 +95,19 @@ public MockMultipartHttpServletRequestBuilder file(MockMultipartFile file) {
return this;
}

/**
* Add {@link Part} components to the request.
* @param parts one or more parts to add
* @since 5.0
*/
public MockMultipartHttpServletRequestBuilder part(Part... parts) {
Assert.notEmpty(parts, "'parts' must not be empty");
for (Part part : parts) {
this.parts.add(part.getName(), part);
}
return this;
}

@Override
public Object merge(Object parent) {
if (parent == null) {
Expand All @@ -97,7 +118,10 @@ public Object merge(Object parent) {
if (parent instanceof MockMultipartHttpServletRequestBuilder) {
MockMultipartHttpServletRequestBuilder parentBuilder = (MockMultipartHttpServletRequestBuilder) parent;
this.files.addAll(parentBuilder.files);
parentBuilder.parts.keySet().stream().forEach(name ->
this.parts.putIfAbsent(name, parentBuilder.parts.get(name)));
}

}
else {
throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]");
Expand All @@ -112,10 +136,17 @@ public Object merge(Object parent) {
*/
@Override
protected final MockHttpServletRequest createServletRequest(ServletContext servletContext) {

MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(servletContext);
for (MockMultipartFile file : this.files) {
request.addFile(file);
this.files.stream().forEach(request::addFile);
this.parts.values().stream().flatMap(Collection::stream).forEach(request::addPart);

if (!this.parts.isEmpty()) {
new StandardMultipartHttpServletRequest(request)
.getMultiFileMap().values().stream().flatMap(Collection::stream)
.forEach(request::addFile);
}

return request;
}

Expand Down
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -208,7 +208,28 @@ public static MockHttpServletRequestBuilder request(String httpMethod, URI uri)
* Create a {@link MockMultipartHttpServletRequestBuilder} for a multipart request.
* @param urlTemplate a URL template; the resulting URL will be encoded
* @param uriVars zero or more URI variables
* @since 5.0
*/
public static MockMultipartHttpServletRequestBuilder multipart(String urlTemplate, Object... uriVars) {
return new MockMultipartHttpServletRequestBuilder(urlTemplate, uriVars);
}

/**
* Create a {@link MockMultipartHttpServletRequestBuilder} for a multipart request.
* @param uri the URL
* @since 5.0
*/
public static MockMultipartHttpServletRequestBuilder multipart(URI uri) {
return new MockMultipartHttpServletRequestBuilder(uri);
}

/**
* Create a {@link MockMultipartHttpServletRequestBuilder} for a multipart request.
* @param urlTemplate a URL template; the resulting URL will be encoded
* @param uriVars zero or more URI variables
* @deprecated in favor of {@link #multipart(String, Object...)}
*/
@Deprecated
public static MockMultipartHttpServletRequestBuilder fileUpload(String urlTemplate, Object... uriVars) {
return new MockMultipartHttpServletRequestBuilder(urlTemplate, uriVars);
}
Expand All @@ -217,11 +238,14 @@ public static MockMultipartHttpServletRequestBuilder fileUpload(String urlTempla
* Create a {@link MockMultipartHttpServletRequestBuilder} for a multipart request.
* @param uri the URL
* @since 4.0.3
* @deprecated in favor of {@link #multipart(URI)}
*/
@Deprecated
public static MockMultipartHttpServletRequestBuilder fileUpload(URI uri) {
return new MockMultipartHttpServletRequestBuilder(uri);
}


/**
* Create a {@link RequestBuilder} for an async dispatch from the
* {@link MvcResult} of the request that started async processing.
Expand Down
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,6 +16,7 @@

package org.springframework.test.web.servlet.samples.standalone;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
Expand All @@ -26,10 +27,13 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.junit.Test;

import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockPart;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.ui.Model;
Expand All @@ -40,14 +44,15 @@
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.multipart.MultipartFile;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

/**
* @author Rossen Stoyanchev
*/
public class FileUploadControllerTests {
public class MultipartControllerTests {

@Test
public void multipartRequest() throws Exception {
Expand All @@ -57,8 +62,25 @@ public void multipartRequest() throws Exception {
byte[] json = "{\"name\":\"yeeeah\"}".getBytes(StandardCharsets.UTF_8);
MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json);

MockMvc mockMvc = standaloneSetup(new MultipartController()).build();
mockMvc.perform(fileUpload("/test").file(filePart).file(jsonPart))
standaloneSetup(new MultipartController()).build()
.perform(multipart("/test-multipartfile").file(filePart).file(jsonPart))
.andExpect(status().isFound())
.andExpect(model().attribute("fileContent", fileContent))
.andExpect(model().attribute("jsonContent", Collections.singletonMap("name", "yeeeah")));
}

@Test
public void multipartRequestWithServletParts() throws Exception {
byte[] fileContent = "bar".getBytes(StandardCharsets.UTF_8);
MockPart filePart = new MockPart("file", "orig", new ByteArrayInputStream(fileContent));

byte[] json = "{\"name\":\"yeeeah\"}".getBytes(StandardCharsets.UTF_8);
MockPart jsonPart = new MockPart("json", "json", new ByteArrayInputStream(json));
jsonPart.getHeaders().setContentType(MediaType.APPLICATION_JSON);

standaloneSetup(new MultipartController()).build()
.perform(multipart("/test-multipartfile").part(filePart).part(jsonPart))
.andExpect(status().isFound())
.andExpect(model().attribute("fileContent", fileContent))
.andExpect(model().attribute("jsonContent", Collections.singletonMap("name", "yeeeah")));
}
Expand All @@ -72,15 +94,16 @@ public void multipartRequestWrapped() throws Exception {
MockMvc mockMvc = standaloneSetup(new MultipartController()).addFilter(filter).build();

Map<String, String> jsonMap = Collections.singletonMap("name", "yeeeah");
mockMvc.perform(fileUpload("/testJson").file(jsonPart)).andExpect(model().attribute("json", jsonMap));
mockMvc.perform(multipart("/test-json").file(jsonPart)).andExpect(model().attribute("json", jsonMap));
}


@Controller
@SuppressWarnings("unused")
private static class MultipartController {

@RequestMapping(value = "/test", method = RequestMethod.POST)
public String processMultipart(@RequestParam MultipartFile file,
@RequestMapping(value = "/test-multipartfile", method = RequestMethod.POST)
public String processMultipartFile(@RequestParam MultipartFile file,
@RequestPart Map<String, String> json, Model model) throws IOException {

model.addAttribute("jsonContent", json);
Expand All @@ -89,7 +112,17 @@ public String processMultipart(@RequestParam MultipartFile file,
return "redirect:/index";
}

@RequestMapping(value = "/testJson", method = RequestMethod.POST)
@RequestMapping(value = "/test-part", method = RequestMethod.POST)
public String processPart(@RequestParam Part part,
@RequestPart Map<String, String> json, Model model) throws IOException {

model.addAttribute("jsonContent", json);
model.addAttribute("fileContent", part.getInputStream());

return "redirect:/index";
}

@RequestMapping(value = "/test-json", method = RequestMethod.POST)
public String processMultipart(@RequestPart Map<String, String> json, Model model) {
model.addAttribute("json", json);
return "redirect:/index";
Expand Down
2 changes: 1 addition & 1 deletion src/asciidoc/testing.adoc
Expand Up @@ -3986,7 +3986,7 @@ request but rather you have to set it up:
[source,java,indent=0]
[subs="verbatim,quotes"]
----
mockMvc.perform(fileUpload("/doc").file("a1", "ABC".getBytes("UTF-8")));
mockMvc.perform(multipart("/doc").file("a1", "ABC".getBytes("UTF-8")));
----

You can specify query parameters in URI template style:
Expand Down

0 comments on commit eabd8a2

Please sign in to comment.