Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 220
Juan Caleb Rizo Vilchis Avatar asked May 18 '16 16:05

Juan Caleb Rizo Vilchis


1 Answers

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.

like image 116
heroin Avatar answered Nov 11 '22 10:11

heroin