我正在尝试使用Spring MVC 3.2创建一个RESTful控制器端点来上传文件以及该文件的元数据映射。定义如下:
@Controller
@RequestMapping("/file")
public class FileServiceController {
@RequestMapping(value="/upload", method=RequestMethod.POST)
@ResponseBody
public void upload(@RequestParam MultipartFile file,
@RequestParam String fileType,
@RequestParam(value="metadata") Map<String, List<String>> metadata) {
// TODO: stuff with things
}
}
然后我试着像这样测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class })
@WebAppConfiguration
public class ProductIngestServiceControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Mock
private FileServiceController controller;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void testUpload() {
MockMultipartFile mockFile = new MockMultipartFile("file", "This is a test file".getBytes());
Map<String, List<String>> metadata = new HashMap<>();
metadata.put("custom0", Arrays.asList("test1", "test2"));
metadata.put("custom1", Arrays.asList("test3", "test4", "test5"));
metadata.put("custom2", Arrays.asList("test6"));
Gson gson = new Gson();
String mapStr = gson.toJson(metadata);
mockMvc.perform(fileUpload(baseURL + "/test")
.file(mockFile)
.param("fileType", "test_type")
.param("metadata", mapStr))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
}
我希望地图只包含“customX”条目,但它包含所有请求参数(MultipartFile除外)。
如果我尝试:
public void upload(@RequestParam MultiValueMap parameters) {
...
}
MultipartFile也不包含在该地图中。
我是以错误的方式来做这件事的吗?我目前唯一能提出的解决方案是只使用String作为元数据RequestParam并执行以下操作:
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory();
JsonParser jp = factory.createJsonParser(testMap);
Map<String, List<String>> map = jp.readValueAs(Map.class);
但感觉很脏。
非常感谢任何帮助。谢谢!
答案 0 :(得分:0)
使用MockHttpServletRequest。
@Before
public void before() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.dispatchOptions(true).build();
MockHttpServletRequest request;= new MockHttpServletRequest();
Map<String, List<String>> metadata=request.getParameter("metadata");
}