lundi 1 janvier 2018

Sending an object with files using the MockMvc test

I want to send an object to the controller that has several lists with files and several fields with plain text.

public class ContributionNew<T extends MovieInfoDTO> {
    private List<T> elementsToAdd;
    private Map<Long, T> elementsToUpdate;
    private Set<Long> idsToDelete;
    private Set<String> sources;
    private String comment;
}

public class Photo extends MovieInfoDTO {
    private MultipartFile photo;
}

@PostMapping(value = "/{id}/contributions/photos")
@ResponseStatus(HttpStatus.CREATED)
public
ResponseEntity<Void> createPhotoContribution(
        @ApiParam(value = "The movie ID", required = true)
        @PathVariable("id") final Long id,
        @ApiParam(value = "The contribution", required = true)
        @RequestBody @Valid final ContributionNew<Photo> contribution
) {

I want to create a test to send an object, but I do not know how to finish it.

@Test
public void testCreatePhotoContribution() throws Exception {
    ContributionNew<Photo> contribution = new ContributionNew<>();
    MockMultipartFile multipartFile = new MockMultipartFile("photo", "C:\\Users\\Jonatan\\Pictures\\2.png",
            "image/png", "Spring Framework".getBytes());
    Photo.Builder photoBuilder = new Photo.Builder(
            multipartFile
    );
    contribution.getElementsToAdd().add(photoBuilder.build());

    mockMvc
            .perform(fileUpload("/api/v1.0/movies/{id}/contributions/photos", 1)
                .contentType(...)
                .content(...))
            .andExpect(status().isCreated());
}

I do not know how to set the correct type for the transmitted data, set the content. Only tutorials about sending only files (not in objects) are available. But there are no guides where the file is one of the fields in the object. How to do it?

Aucun commentaire:

Enregistrer un commentaire