简体   繁体   English

Spring Boot:使用 TestRestTemplate 测试分页结果

[英]Spring boot: testing paged results using TestRestTemplate

I have a resource A that have a controller containing an endpoint for retrieving paged A items:我有一个资源 A,它有一个控制器,其中包含一个用于检索分页 A 项目的端点:

      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.当我尝试创建集成测试并使用 TestRestTemplate 调用此端点时,我遇到了一个问题,因为无法实例化Page对象。

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.我想Page无法实例化这一事实很正常,但这会限制使用 Spring Boot 分页结果时的可测试性。

Make changes in the response of the controller from Page<T> to List<T> .将控制器的响应从Page<T>更改为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然后将您使用 API 的位置从列表转换为页面

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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