From 905f606acab04f5e5e70530026345a9344d933c6 Mon Sep 17 00:00:00 2001 From: GuilhermeBauer16 Date: Tue, 6 Aug 2024 18:46:19 -0300 Subject: [PATCH] =?UTF-8?q?feat/i31:=20cria=C3=A7=C3=A3o=20do=20m=C3=A9tod?= =?UTF-8?q?o=20findAll=20com=20pagina=C3=A7=C3=A3o=20e=20tamb=C3=A9m=20for?= =?UTF-8?q?am=20implementados=20os=20testes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rest/controller/ShelterController.java | 43 +++++++++++++ .../controller/imp/ShelterControllerImpl.java | 10 +++- .../rest/repository/ShelterRepository.java | 14 +++++ .../rest/service/ShelterEntityService.java | 17 +++++- .../impl/ShelterEntityServiceImpl.java | 15 +++++ .../ShelterRepositoryIntegrationTest.java | 22 +++++++ .../impl/ShelterEntityServiceImplTest.java | 60 +++++++++++++++++-- 7 files changed, 175 insertions(+), 6 deletions(-) diff --git a/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/controller/ShelterController.java b/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/controller/ShelterController.java index bcca5a8..7851a57 100644 --- a/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/controller/ShelterController.java +++ b/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/controller/ShelterController.java @@ -10,6 +10,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -18,6 +20,7 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.server.ResponseStatusException; + /** * Interface que define as operações de gerenciamento de abrigos. *

@@ -169,4 +172,44 @@ public interface ShelterController { }) ResponseEntity findShelterByUserResponsibleEmail(@PathVariable("userResponsibleEmail") String userResponsibleEmail); + /** + * Método GET para encontrar todos os abrigos cadastrados. + *

+ * Este método recebe um {@link Pageable} que para que seja feito a paginação da pagina + * e retorna como resposta todos os {@link ShelterInformationResponse} cadastrados com paginação. + *

+ *

+ * O método retornará um objeto JSON com os seguintes campos: + *

+ *

+ * + * @return Retorna um {@link ResponseEntity} que encapsula a resposta do abrigo encontrado. Esta + * resposta inclui o status HTTP da operação, bem como um corpo que é uma representação JSON + * do abrigo. + * + * @see Pageable + * @see Page + */ + + @GetMapping + @Operation( + summary = "Encontra todos os abrigos cadastrados", + description = "Este endpoint é responsável por encontrar todos os abrigos cadastrados e paginá-los, " + + "utilizando os dados recebidos por meio de uma requisição do tipo GET.", + tags = "Abrigos" + ) + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Abrigos encontrados com sucesso!", + content = @Content(schema = @Schema(implementation = ShelterInformationResponse.class)) + ) + }) + ResponseEntity> findAll(Pageable pageable); + } diff --git a/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/controller/imp/ShelterControllerImpl.java b/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/controller/imp/ShelterControllerImpl.java index eda0a11..b8aa180 100644 --- a/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/controller/imp/ShelterControllerImpl.java +++ b/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/controller/imp/ShelterControllerImpl.java @@ -5,9 +5,11 @@ import diegosneves.github.conectardoacoes.adapters.rest.exception.ShelterEntityFailuresException; import diegosneves.github.conectardoacoes.adapters.rest.request.ReceiveDonationRequest; import diegosneves.github.conectardoacoes.adapters.rest.request.ShelterCreationRequest; -import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterInformationResponse; import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterCreatedResponse; +import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterInformationResponse; import diegosneves.github.conectardoacoes.adapters.rest.service.ShelterEntityService; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; @@ -56,4 +58,10 @@ public ResponseEntity findShelterByUserResponsibleEm shelterEntityService.findShelterByUserResponsibleEmail(userResponsibleEmail); return ResponseEntity.ok(shelterRecoveryByUserResponsibleEmail); } + + @Override + public ResponseEntity> findAll(Pageable pageable) { + Page allPageableShelters = shelterEntityService.findAll(pageable); + return ResponseEntity.ok(allPageableShelters); + } } diff --git a/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/repository/ShelterRepository.java b/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/repository/ShelterRepository.java index aeaf830..4b0e655 100644 --- a/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/repository/ShelterRepository.java +++ b/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/repository/ShelterRepository.java @@ -13,6 +13,8 @@ import diegosneves.github.conectardoacoes.core.exception.UuidUtilsException; import diegosneves.github.conectardoacoes.core.utils.UuidUtils; import diegosneves.github.conectardoacoes.core.utils.ValidationUtils; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @@ -212,4 +214,16 @@ default void deleteEntityById(String id) { */ Optional findShelterEntitiesByResponsibleUser_Email(String responsibleUserEmail); + /** + * Este método é usado para buscar todos os abrigos cadastrados e devolvê-los paginados. + *

+ * Esse método recupera todas as entidades de {@link ShelterEntity} presentes no banco de dados, usando o método semelhante ao {@code findAll}. + * No entanto, ele recebe um parâmetro {@link Pageable} para que possa ser feita a paginação e também a ordenação (sort) de todos os shelters. + *

+ * + * @return Um {@link Page} de todos os {@link ShelterEntity} registrados no banco de dados. Se não houver entidades de abrigo no banco de dados, retorna uma lista vazia. + */ + + Page findAll(Pageable pageable); + } diff --git a/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/service/ShelterEntityService.java b/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/service/ShelterEntityService.java index de3db6d..d972531 100644 --- a/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/service/ShelterEntityService.java +++ b/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/service/ShelterEntityService.java @@ -5,8 +5,10 @@ import diegosneves.github.conectardoacoes.adapters.rest.model.DonationEntity; import diegosneves.github.conectardoacoes.adapters.rest.request.ReceiveDonationRequest; import diegosneves.github.conectardoacoes.adapters.rest.request.ShelterCreationRequest; -import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterInformationResponse; import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterCreatedResponse; +import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterInformationResponse; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; /** * Interface para a criação de um novo abrigo no sistema. @@ -71,4 +73,17 @@ public interface ShelterEntityService { ShelterInformationResponse findShelterByUserResponsibleEmail(String userResponsibleEmail); + /** + * Método utilizado para encontrar todos os abrigos com paginação. + * Recupera uma página de informações de abrigos do sistema com base nas informações de paginação fornecidas. + * Este método é responsável por retornar uma lista paginada de {@link ShelterInformationResponse}, + * que contém detalhes sobre os abrigos registrados no sistema. + * + * @param pageable um objeto {@link Pageable} que define as informações de paginação, como número da página + * e tamanho da página, para controlar o retorno das informações de abrigos. + * @return uma página de objetos {@link ShelterInformationResponse} contendo as informações dos abrigos. + */ + + Page findAll(Pageable pageable); + } diff --git a/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/service/impl/ShelterEntityServiceImpl.java b/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/service/impl/ShelterEntityServiceImpl.java index 543bd67..9013fa0 100644 --- a/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/service/impl/ShelterEntityServiceImpl.java +++ b/src/main/java/diegosneves/github/conectardoacoes/adapters/rest/service/impl/ShelterEntityServiceImpl.java @@ -35,8 +35,12 @@ import diegosneves.github.conectardoacoes.core.utils.ValidationUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; +import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -308,6 +312,17 @@ public ShelterInformationResponse findShelterByUserResponsibleEmail(String userR return BuilderMapper.mapTo(getShelterInformationResponseMapper(), currentShelterByResponsibleEmail); } + @Override + public Page findAll(Pageable pageable) { + + Page allShelterWithPageable = repository.findAll(pageable); + List content = allShelterWithPageable.getContent(); + List informationResponses = content.stream() + .map(getShelterInformationResponseMapper()::mapFrom).toList(); + + return new PageImpl<>(informationResponses, pageable, allShelterWithPageable.getTotalElements()); + } + /** * Este método é responsável por criar uma nova instância de um objeto {@link ShelterInformationResponseFromShelterEntityMapper}. *

diff --git a/src/test/java/diegosneves/github/conectardoacoes/adapters/rest/repository/ShelterRepositoryIntegrationTest.java b/src/test/java/diegosneves/github/conectardoacoes/adapters/rest/repository/ShelterRepositoryIntegrationTest.java index e929bcd..846e94b 100644 --- a/src/test/java/diegosneves/github/conectardoacoes/adapters/rest/repository/ShelterRepositoryIntegrationTest.java +++ b/src/test/java/diegosneves/github/conectardoacoes/adapters/rest/repository/ShelterRepositoryIntegrationTest.java @@ -23,6 +23,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.lang.reflect.Method; @@ -438,4 +440,24 @@ void shouldNotFindShelterEntityByUserEmailWhenEmailIsIncorrect() { } + @Test + void shouldReturnFindAllWithAllOfPagedShelterEntity(){ + + persistEntity(new AddressEntityMapper(), this.address); + persistEntity(new UserEntityMapper(), this.user); + persistEntity(new ShelterEntityMapper(), this.shelter); + Pageable pageable = Pageable.ofSize(10); + + Page allShelters = shelterRepository.findAll(pageable); + + ShelterEntity shelterEntityRecovery = allShelters.getContent().get(0); + assertNotNull(allShelters); + assertEquals(this.shelter.getId(), shelterEntityRecovery.getId()); + assertEquals(this.shelter.getShelterName(), shelterEntityRecovery.getShelterName()); + assertNotNull(this.shelter.getUser()); + assertNotNull(this.shelter.getAddress()); + + + } + } diff --git a/src/test/java/diegosneves/github/conectardoacoes/adapters/rest/service/impl/ShelterEntityServiceImplTest.java b/src/test/java/diegosneves/github/conectardoacoes/adapters/rest/service/impl/ShelterEntityServiceImplTest.java index 4f6d956..7c0ae00 100644 --- a/src/test/java/diegosneves/github/conectardoacoes/adapters/rest/service/impl/ShelterEntityServiceImplTest.java +++ b/src/test/java/diegosneves/github/conectardoacoes/adapters/rest/service/impl/ShelterEntityServiceImplTest.java @@ -32,16 +32,34 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import org.mockito.*; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @ExtendWith(SpringExtension.class) class ShelterEntityServiceImplTest { @@ -501,5 +519,39 @@ void shouldThrowShelterEntityFailuresExceptionWhenTheEmailPassIsNull(){ } + @Test + void testFindAll_When_WithPageable_ShouldReturnAPageableOfAllShelterInformationResponse(){ + + DonationEntity firstDonation = new DonationEntity(); + firstDonation.setDescription(DESCRIPTION); + firstDonation.setAmount(AMOUNT); + + List donations = List.of(firstDonation); + + ShelterEntity shelterEntity = generateShelterEntity(); + shelterEntity.setDonations(donations); + + List shelterEntityList = List.of(shelterEntity); + + when(repository.findAll(any(Pageable.class))).thenReturn(new PageImpl<>(shelterEntityList)); + + Page allShelters = service.findAll(PageRequest.of(0, 10)); + + verify(repository,times(1)).findAll(any(Pageable.class)); + + ShelterInformationResponse shelterInformationResponse = allShelters.getContent().get(0); + + assertNotNull(allShelters); + assertEquals(1, allShelters.getTotalElements()); + + assertEquals(SHELTER_NAME, shelterInformationResponse.getShelterName()); + assertEquals(USER_NAME, shelterInformationResponse.getResponsibleName()); + assertEquals(USER_EMAIL, shelterInformationResponse.getResponsibleEmail()); + assertEquals(1, shelterInformationResponse.getDonationDTOS().size()); + assertEquals(DESCRIPTION, shelterInformationResponse.getDonationDTOS().get(0).getDescription()); + assertEquals(AMOUNT, shelterInformationResponse.getDonationDTOS().get(0).getAmount()); + + } + }