jeudi 11 janvier 2018

Spring Data pagination issue while mapping entity back to DTO

I've implemented a paginated REST API and trying to consume it with RestTemplate while testing. Also I'm mapping domain objects to DTOs in the service layer so that Page<ProductDto> is returned by getPage(Pageable pageRequest) method call.

  public Page<ProductDto> getPage(Pageable pageRequest) {
        Page<Product> products = productRepository.findAll(pageRequest);
        return mapDomainPageIntoDTOPage(products);
    }

    private Page<ProductDto> mapDomainPageIntoDTOPage(Page<Product> productsPage) {
        List<ProductDto> productDtoList = mapEntitiesToDTOs(productsPage.getContent());
        return new PageImpl<>(productDtoList); // getting NullPointerException here
    }

    private List<ProductDto> mapEntitiesToDTOs(List<Product> entities) {
        return entities.stream()
                .map(domainToDtoMapper::mapProductToDto)
                .collect(toList());
    }

The following test keeps failing with AssertionError: expected [2] but found [0]. After debugging I figured out that the problem is most likely with the mapDomainPageIntoDTOPage() method. NullPointerException with the message Content must not be null! is thrown when the line return new PageImpl<>(productDtoList); gets executed. However the size of productDtoList size is 2.

What should I modify in the mapping logic to make it behave correctly?

@Test
    public void getPage() {
        Pageable pageRequest = new PageRequest(0, 2);
        Product product1 = new Product().setId(1L);
        Product product2 = new Product().setId(2L);

        Page<Product> products = new RestResponsePage<>(Arrays.asList(product1, product2));

        when(productRepository.findAll(pageRequest)).thenReturn(products);

        ResponseEntity<RestResponsePage<ProductDto>> result = restTemplate.exchange("/product/?page=0&size=2",
                HttpMethod.GET, null, new ParameterizedTypeReference<RestResponsePage<ProductDto>>() {});

        verify(productRepository, times(1)).findAll(pageRequest);

        assertEquals(HttpStatus.OK, result.getStatusCode());
        assertEquals(result.getBody().getContent().size(), products .getContent().size());
        assertEquals(result.getBody().getTotalElements(), products .getTotalElements());
    }

Aucun commentaire:

Enregistrer un commentaire