0

Using spring-boot 2.2.4.

I have a SpringMvc Controller that returns pageable objects:

@RestController
@RequestMapping("/call-data")
public class CallDataController {
  @GetMapping
  public Page<CallDataDto> findAll(Pageable page) {
...

Trying to test it with MockMvc:

ObjectMapper mapper = new ObjectMapper();
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/call-data")).andReturn();
Page<CallDataDto> myDtos = mapper.readValue(mvcResult.getResponse().getContentAsString(), TypeUtils.pageTypeRef());

...

public class TypeUtils {
  public static <T> TypeReference<RestResponsePage<T>> pageTypeRef() {
      return new TypeReference<>() {
};
}

But instead of page with dto objects I get a page with LinkedHashMaps.

So how to get the page with dto objects?

kostepanych
  • 2,229
  • 9
  • 32
  • 47

1 Answers1

0

Similar question: ObjectMapper using TypeReference not working when passed type in generic method

You can solve the problem by replacing the type parameter(T) with CallDataDto.

public class TypeUtils {
  public static TypeReference<RestResponsePage<CallDataDto>> pageTypeRef() {
      return new TypeReference<>() {
};
}

Type parameters(e.g. <T>) don't exist at runtime so you have to replace them with some concrete values so that Jackson can obtain full generics type information.

Tomoki Sato
  • 578
  • 4
  • 11