使用MockMvc测试发送带有文件的对象

时间:2018-01-01 23:34:05

标签: java spring spring-mvc testing mockmvc

我想将一个对象发送到控制器,该控制器有几个包含文件的列表和几个带有纯文本的字段。

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
) {

我想创建一个发送对象的测试,但我不知道如何完成它。

@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(post("/api/v1.0/movies/{id}/contributions/photos", 1)
                .contentType(...)
                .content(...))
            .andExpect(status().isCreated());
}

我不知道如何为传输的数据设置正确的类型,设置内容。只有tutorials关于仅发送文件(不在对象中)可用。但是没有指南,文件是对象中的一个字段。怎么做?

0 个答案:

没有答案