简体   繁体   中英

Spring boot: testing paged results using TestRestTemplate

I have a resource A that have a controller containing an endpoint for retrieving paged A items:

      public ResponseEntity getAllAs(
      @PageableDefault(size = 25, value = 0) Pageable pageable) {
        Page<A> pagedAs = .....
        return ResponseEntity.ok(pagedAs);
  }

When I have tried to create an integration test and calling this endpoint using TestRestTemplate, I got a problem because a Page object cannot be instantiated.

Here is the call:

    ResponseEntity<Page> response =  template.getForEntity("/api/as,
            Page.class );

And here is the exception:

  com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.domain.Page` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (PushbackInputStream); line: 1, column: 1]

I guess it is a normal regarding the fact that Page cannot be instantiated but this constrains the testability when using spring boot paginated results.

Make changes in the response of the controller from Page<T> to List<T> .

public ResponseEntity getAllAs(
       @PageableDefault(size = 25, value = 0) Pageable pageable) {
       Page < A > pagedAs = .....
       return ResponseEntity.ok(pagedAs);
   }

Then convert where you are consuming the API from List to Page

Page<T> page = new PageImpl<>(list);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM