MockMvc - 使用复杂对象调用查询

问题描述 投票:1回答:1

我想向控制器发送一个由文件和简单类型组成的复杂对象。

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());
}

我不知道如何发送@ResuestBody这样的对象?我不知道如何完成这个测试。

java spring rest spring-mvc spring-boot
1个回答
0
投票

你可以做这样的事情。

 ObjectMapper = new ObjectMapper();        // You can also Autowire this 
 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    mockMvc
     .perform(post("/api/v1.0/movies/{id}/contributions/photos", 1)
     .contentType(MediaType.APPLICATION_JSON)                   
     .content(objectMapper.writeValueAsString(contribution)))
     .andExpect(status().isCreated());
© www.soinside.com 2019 - 2024. All rights reserved.