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

时间:2018-01-02 14:35:05

标签: java spring rest spring-mvc spring-boot

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

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这样的对象?我不知道如何完成这个测试。

1 个答案:

答案 0 :(得分: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());