Я пытаюсь написать модульные тесты для контроллера весной mvc, который принимает многочастные данные формы с файлом вместе с другими данными формы. Я могу отправить свой запрос контроллеру во время тестирования, но не могу получить доступ к файлу или отправленным данным. Элементы файлов, полученные в контроллере, кажутся пустыми, отмеченными как fileItemsEmpty в приведенном ниже коде. Я могу нажать api и отправить фактические данные из пользовательского интерфейса. Любая помощь приветствуется.
Код контроллера:
@RequestMapping(value = "/upload-file", method = RequestMethod.POST, produces = CommonConstants.PRODUCES_JSON)
@ResponseBody
public String uploadFile(HttpServletRequest request, @NonNull Principal principal) throws Exception {
try {
String attribute1 = "";
String attribute2 = "";
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
fileItemsEmpty -> for (FileItem item : items) {
if(item.isFormField()) {
switch (item.getFieldName()) {
case "Attribute1":
attribute1 = item.getString("UTF-8");
break;
case "Attribute2":
attribute2 = item.getString("UTF-8");
break;
default:
log.info("Unknown Attribute received {}",
item.getFieldName());
}
} else {
BufferedReader br = new BufferedReader(new InputStreamReader(item.getInputStream(), StandardCharsets.UTF_8.name()));
String line = br.readLine();
while (line != null) {
//some computation from the file
}
br.close();
}
}
} catch (FileUploadException e) {
e.printStacktrace();
}
//Perform computation based on attribute1 and attribute2 and return string data.
}
Модульный тест:
@Test
public void testfileUpload() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "file.txt", "", "file contents".getBytes());
MockMultipartFile attribute1 = new MockMultipartFile("Attribute1", "", "", "attribute1 value".getBytes());
MockMultipartFile attribute2 = new MockMultipartFile("Attribute2", "", "", "attribute2 value".getBytes());
HashMap<String, String> contentTypeParams = new HashMap<String, String>();
contentTypeParams.put("boundary", "----WebKitFormBoundary");
MediaType mediaType = new MediaType("multipart", "form-data", contentTypeParams);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/upload-file")
.file(file)
.file(attribute1)
.file(attribute2)
.contentType(mediaType)
.principal(principal))
.andExpect(status().isOk()).andReturn();
}
Angular код:
uploadFile(event) {
event.target.disabled = true;
var formData = new FormData();
formData.append('Attribute1', 'value1');
formData.append('Attribute2', value2);
formData.append('file', $('#fileInput')[0].files[0]);
this.http.post<any>("/upload-file", formData);
}