1

I want to test my Spring Controller that has input json and multipart file, however even if the function works, I can't get the test works

I tried using MockMvcRequestBuilders.fileUpload but the test always get 405

The controller:

 @PutMapping(value = "/upload", consumes = {"multipart/form-data"})
  public BaseResponse<SomeModel> updateSomeModelContent(
      @ApiIgnore @Valid @ModelAttribute MandatoryRequest mandatoryRequest,
      @PathVariable("id") String id,
      @RequestParam("file") MultipartFile file,
      @RequestParam("json") String json) throws IOException {
    final CommonSomeModelRequest request = JSONHelper.convertJsonInStringToObject(json, CommonSomeModelRequest.class);
    return makeResponse(someModelSer.updateContent(id, request, mandatoryRequest, file));
  }

The test:

  @Test
  public void updateCountryContentSuccessTest() throws Exception {
    MockMultipartFile file1 = new MockMultipartFile("file", "filename-1.jpeg", "image/jpeg", "some-image".getBytes());
    MockMultipartFile file2 = new MockMultipartFile("json", "", "application/json","{\"exampleAttr\": \"someValue\"}".getBytes());

    when(this.someModelService
        .updateContent(id, request, MANDATORY_REQUEST, file1))
        .thenReturn(someModelUpdatedContent);

    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders
        .fileUpload("/upload/{id}", id)
        .file(file1)
        .file(file2)
        .requestAttr("mandatory", MANDATORY_REQUEST);

    this.mockMvc.perform(builder)
        .andExpect(status().isOk());

    verify(this.someModelService)
        .updateContent(id, request, MANDATORY_REQUEST, file1);
  }

The result status is always 405, I don't know how to make it 200

1 Answers1

0

MockMvcRequestBuilders.multipart(...) create MockMultipartHttpServletRequestBuilder which support only POST. But in your controller you use POST. You should change PUT to POST mapping in the rest controller.

Also according to RFCs we should use POST instead of PUT on multipart upload. Have a look at Spring MVC Framework: MultipartResolver with PUT method

i.bondarenko
  • 3,442
  • 3
  • 11
  • 21