How to make unit test multipart with a PUT request using Spring MVC and Spock?
Asked Answered
S

1

6

I have a controller like this one:

@RestController
@RequestMapping('/v1/document')
class DocumentV1Controller {
  @PutMapping
  HttpEntity<Document> newdoc(
    @RequestHeader Map<String, String> headers, @RequestParam('document') MultipartFile multipartFile) {
  }
}

And I wan to test it using Spring MVC Test and Spock but I just can't figured out how to build a MockMultipartHttpServletRequestBuilder changing the HttpMethod from POST to PUT request.

This is the Spock specification:

class DocumentV1ControllerSpec extends BaseControllerSpec {
  Should 'test and document good request on /v1/document endpoint'() {
    given:
      File file = new File('./src/test/resources/demoC.csv')
      MockMultipartFile multipartFile = new MockMultipartFile('file',file.getBytes())
    when:
      ResultActions result = mockMvc.perform(fileUpload('/v1/document')
        .file(multipartFile))
    then:
      result.andExpect(status().isCreated())
  }
}

The error I get is this:

java.lang.AssertionError: Status expected:<201> but was:<405>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:664)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at gus.rest.api.v1.DocumentV1ControllerSpec.test and document good request on /v1/document endpoint(DocumentV1ControllerSpec.groovy:61)

What can I do to make it work?

Shofar answered 18/5, 2016 at 16:19 Comment(0)
S
1

I am not an expert in spock, however method fileUpload is deprecated now for Spring (at version 5.*).

There is a way to change default POST method for MockMultipartHttpServletRequestBuilder to PUT:

class DocumentV1ControllerSpec extends BaseControllerSpec {
  Should 'test and document good request on /v1/document endpoint'() {
    given:
      File file = new File('./src/test/resources/demoC.csv')
      MockMultipartFile multipartFile = new MockMultipartFile('file', file.getBytes())

      MockMultipartHttpServletRequestBuilder multipart = (MockMultipartHttpServletRequestBuilder) multipart('/v1/document').with(request -> {
        request.setMethod(HttpMethod.PUT);
        return request;
      });
    when:
      ResultActions result = mockMvc.perform(multipart
        .file(multipartFile))
    then:
      result.andExpect(status().isCreated())
  }
}

The trick is to use with(RequestPostProcessor postProcessor) to modify request and set method PUT to it.

Sentimentalism answered 23/1, 2019 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.