9 Ağustos 2021 Pazartesi

SpringTest MockMultipartFile Sınıfı

Örnek
Elimizde şöyle bir kod olsun
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ApiOperation(value = "Saves File instance.", tags = {"File"})
@ApiResponses({
        @ApiResponse(code = 201, message = "A File was successfully created.")
})
public ResponseEntity create(@RequestPart(name = "model") @Valid FileCreationDto model, 
                             @RequestPart(name = "file") MultipartFile file) {
    try {
        model.setData(file.getBytes());
    } catch (IOException e) {
        return ResponseEntity.badRequest().build();
    }

  File fileCreated = fileService.create(model, file.getOriginalFilename());
  return ResponseEntity.status(HttpStatus.CREATED).body(fileCreated);
}
Şöyle yaparız
@Test
public void create_withName_OK() throws Exception {
  
  MockMultipartFile model = ...;
  MockMultipartFile file = ...;

  MvcResult result = mvc.perform(
    MockMvcRequestBuilders.multipart("/api/files")
      .file(model)
      .file(file))
      .andDo(print())
      .andExpect(status().isCreated())
      .andReturn();

  File parsed = jsonMapper.readValue(result.getResponse().getContentAsByteArray(), 
    new TypeReference<>() {});

  ...
}


Hiç yorum yok:

Yorum Gönder