简体   繁体   中英

Spring Rest Template is not returning the data

I am trying to write an integration test for my spring application, I have an api which insert some default data, I run call this api after my test gets initialized

@PostConstruct
public void inti() {
    ResponseEntity<String> response = restTemplate.getForEntity("/api/default", String.class);
    assertEquals("Default values are not inserted successfully", "lala", response.getBody());
}

This passed and I can see in the database default values.

In my test I try to fetch some data but the returned data is 0 although I tested the api manually and its working

@Test
public void shouldReturnDeliveryNotes() {
    ResponseEntity<PagedResources<DeliveryNote>> allDeliveryNotes = restTemplate.exchange("/api/deliverynotes/all?start=0&length=1000",HttpMethod.GET,null,  new ParameterizedTypeReference<PagedResources<DeliveryNote>>() {});
    assertNotEquals("Should have default delivery notes", 0, allDeliveryNotes.getBody().getContent().size());   
}

I put some log in the api to see the returned data size and I see the returned data when the test is run is correct which means my test is hitting the right api and the api fetch the data.

@GetMapping("/all")
public ResponseEntity<Page<DeliveryNoteDTO>> getAllDeliveryNote(@RequestParam(value = "start", required = false) int start, @RequestParam(value ="length", required = false) int length) {
    Pageable pageable = new OffsetBasedPageRequest(start, (length ==0? Integer.MAX_VALUE: length));
    List<DeliveryNote> page = this.deliveryNoteService.getAllDeliverNotes();
    List<DeliveryNoteDTO> dtoList =page.stream().map(post -> convertToDto(post)).collect(Collectors.toList());
    Page<DeliveryNoteDTO> pageDto = new PageImpl<>(dtoList, pageable, dtoList.size());
    System.out.println("size = "+pageDto.getNumberOfElements());
    return new ResponseEntity<Page<DeliveryNoteDTO>>(pageDto,HttpStatus.OK);
}

Any help is appreciated

The problem is I am returning Page while in my restTemplate I am expecting PagedResources, it would make sense to just return page but I need a concrete class , I would use PageImpl but the problem is that PageImple does not have a default constructor which RestTemplate use to map the response, so What I did I created a new class and extended the PageImpl just as mentioned in the accepted answer of this question

Spring RestTemplate with paginated API

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