Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/main/java/br/com/db/petcontrol/controller/PetsController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,21 @@

import br.com.db.petcontrol.dto.request.PageableRequestDTO;
import br.com.db.petcontrol.dto.request.PetRequestDTO;
import br.com.db.petcontrol.dto.response.ErrorResponseDTO;
import br.com.db.petcontrol.dto.response.PageResponseDTO;
import br.com.db.petcontrol.dto.response.PetResponseDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.util.UUID;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
Expand Down Expand Up @@ -41,4 +45,22 @@ public interface PetsController {
@GetMapping
ResponseEntity<PageResponseDTO<PetResponseDTO>> findAll(
@ParameterObject PageableRequestDTO pageable);

@Operation(summary = "Buscar um pet", description = "Busca um pet pelo seu id")
@ApiResponse(
responseCode = "200",
description = "Pet buscado com sucesso",
content = @Content(schema = @Schema(implementation = PetResponseDTO.class)))
@ApiResponse(
responseCode = "404",
description = "Pet não encontrado",
content =
@Content(
schema = @Schema(implementation = ErrorResponseDTO.class),
examples =
@ExampleObject(
name = "Pet não encontrado",
value = "{\"messages\": [\"Pet not found\"]}")))
@GetMapping("/{id}")
ResponseEntity<PetResponseDTO> find(@PathVariable UUID id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import br.com.db.petcontrol.dto.response.PageResponseDTO;
import br.com.db.petcontrol.dto.response.PetResponseDTO;
import br.com.db.petcontrol.service.PetsService;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -28,4 +29,10 @@ public ResponseEntity<PageResponseDTO<PetResponseDTO>> findAll(PageableRequestDT
PageResponseDTO<PetResponseDTO> response = petsService.findAll(pageable);
return ResponseEntity.status(HttpStatus.OK).body(response);
}

@Override
public ResponseEntity<PetResponseDTO> find(UUID id) {
PetResponseDTO response = petsService.find(id);
return ResponseEntity.status(HttpStatus.OK).body(response);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
@Schema(description = "Dados de resposta para erros da API")
public record ErrorResponseDTO(
@Schema(description = "Lista de mensagens que detallha os erros ocorridos")
List<String> mensagens) {}
List<String> messages) {}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@RestControllerAdvice
public class GlobalExceptionHandler {
Expand All @@ -31,4 +32,13 @@ public ResponseEntity<ErrorResponseDTO> handleMethodArgumentNotValidException(
ErrorResponseDTO response = new ErrorResponseDTO(errors);
return ResponseEntity.badRequest().body(response);
}

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<ErrorResponseDTO> handleTypeMismatch(
MethodArgumentTypeMismatchException ex) {
String message =
String.format("Valor inválido '%s' para o parâmetro '%s'", ex.getValue(), ex.getName());
ErrorResponseDTO error = new ErrorResponseDTO(List.of(message));
return ResponseEntity.badRequest().body(error);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package br.com.db.petcontrol.repository;

import br.com.db.petcontrol.model.Pets;
import java.util.Optional;
import java.util.UUID;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
Expand All @@ -12,4 +13,7 @@
public interface PetsRepository extends JpaRepository<Pets, UUID> {
@EntityGraph(attributePaths = {"species", "tags"})
Page<Pets> findAll(Pageable pageable);

@EntityGraph(attributePaths = {"species", "tags"})
Optional<Pets> findById(UUID id);
}
3 changes: 3 additions & 0 deletions src/main/java/br/com/db/petcontrol/service/PetsService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
import br.com.db.petcontrol.dto.request.PetRequestDTO;
import br.com.db.petcontrol.dto.response.PageResponseDTO;
import br.com.db.petcontrol.dto.response.PetResponseDTO;
import java.util.UUID;

public interface PetsService {
PetResponseDTO create(PetRequestDTO dto);

PageResponseDTO<PetResponseDTO> findAll(PageableRequestDTO pageable);

PetResponseDTO find(UUID id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ public PageResponseDTO<PetResponseDTO> findAll(PageableRequestDTO pageable) {
return pageMapper.toPageResponseDTO(page);
}

@Override
public PetResponseDTO find(UUID id) {
return petRepository
.findById(id)
.map(petsMapper::toResponse)
.orElseThrow(() -> new NotFoundException("Pet not found"));
}

private List<Tags> findTagsOrCollectErrors(List<UUID> ids, List<String> errors) {
if (ids == null || ids.isEmpty()) {
return List.of();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import br.com.db.petcontrol.dto.response.PageResponseDTO;
import br.com.db.petcontrol.dto.response.PetResponseDTO;
import br.com.db.petcontrol.enums.PetStatus;
import br.com.db.petcontrol.exception.NotFoundException;
import br.com.db.petcontrol.mocks.PageFixture;
import br.com.db.petcontrol.mocks.PetsFixture;
import br.com.db.petcontrol.service.PetsService;
Expand Down Expand Up @@ -43,6 +44,7 @@ class PetsControllerTest {
@MockitoBean private PetsService petsService;

private static final String PETS_URL = "/pets";
private static final String PET_ID_URL = PETS_URL + "/{id}";

@Nested
class CreatePetTests {
Expand Down Expand Up @@ -186,4 +188,43 @@ static Stream<List<PetResponseDTO>> petsProviders() {
List.of());
}
}

@Nested
class FindPetTests {
@Test
void shouldReturnPetByIdSuccessfully() throws Exception {
PetResponseDTO response = PetsFixture.responseDtoBuilder().build();

when(petsService.find(response.id())).thenReturn(response);

mockMvc
.perform(get(PET_ID_URL, response.id()).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(JsonUtils.convertToJson(response)));
}

@Test
void shouldReturnNotFoundWhenPetDoesNotExist() throws Exception {
UUID invalidId = UUID.randomUUID();
String errorMessage = "Pet not found";

when(petsService.find(invalidId)).thenThrow(new NotFoundException(errorMessage));

mockMvc
.perform(get(PET_ID_URL, invalidId).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.messages[0]").value(errorMessage));
}

@Test
void shouldReturnBadRequestWhenIdIsInvalid() throws Exception {
String invalidId = "1";
String expectedMessage = "Valor inválido '1' para o parâmetro 'id'";

mockMvc
.perform(get(PET_ID_URL, invalidId).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.messages[0]").value(expectedMessage));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import br.com.db.petcontrol.dto.response.PageResponseDTO;
import br.com.db.petcontrol.dto.response.PetResponseDTO;
import br.com.db.petcontrol.enums.PetStatus;
import br.com.db.petcontrol.mocks.PetsFixture;
import br.com.db.petcontrol.model.Pets;
import br.com.db.petcontrol.model.Species;
import br.com.db.petcontrol.model.Tags;
Expand Down Expand Up @@ -41,6 +42,7 @@ class PetsIntegrationTest {
@Autowired private TagsRepository tagsRepository;

private static final String PETS_URL = "/pets";
private static final String PET_ID_URL = PETS_URL + "/{id}";

private Species savedSpecies;

Expand Down Expand Up @@ -275,17 +277,7 @@ class FindPetsTests {
@Test
void shouldReturnAllPersistedPetsWithCorrectPagination() {
List<String> names = List.of("Rex", "Luna");
List<Pets> pets =
names.stream()
.map(
name ->
Pets.builder()
.name(name)
.status(PetStatus.AVAILABLE)
.species(savedSpecies)
.tags(List.of())
.build())
.toList();
List<Pets> pets = names.stream().map(name -> builderWithoutId().name(name).build()).toList();

petsRepository.saveAll(pets);

Expand Down Expand Up @@ -328,17 +320,7 @@ void shouldReturnSecondPageWithCorrectPagination() {
int sizePage = 3;

List<String> names = List.of("Rex", "Luna", "Max", "Mel");
List<Pets> pets =
names.stream()
.map(
name ->
Pets.builder()
.name(name)
.status(PetStatus.AVAILABLE)
.species(savedSpecies)
.tags(List.of())
.build())
.toList();
List<Pets> pets = names.stream().map(name -> builderWithoutId().name(name).build()).toList();

petsRepository.saveAll(pets);

Expand All @@ -358,4 +340,28 @@ void shouldReturnSecondPageWithCorrectPagination() {
assertThat(response.getBody().content()).hasSize(1);
}
}

@Nested
class FindPetTests {
@Test
void shouldReturnPetByIdSuccessfully() {
Pets pet = builderWithoutId().build();
Pets savedPet = petsRepository.save(pet);

ResponseEntity<PetResponseDTO> response =
restTemplate.getForEntity(PET_ID_URL, PetResponseDTO.class, savedPet.getId());
PetResponseDTO currentPet = response.getBody();

assertEquals(HttpStatus.OK, response.getStatusCode());
assertThat(currentPet.id()).isEqualTo(savedPet.getId());
assertThat(currentPet.name()).isEqualTo(savedPet.getName());
assertThat(currentPet.species()).isEqualTo(savedPet.getSpecies().getName());
assertThat(currentPet.status()).isEqualTo(savedPet.getStatus());
assertThat(currentPet.tags()).isEmpty();
}
}

public Pets.PetsBuilder builderWithoutId() {
return PetsFixture.builder().id(null).species(savedSpecies);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -272,4 +272,30 @@ void shouldReturnEmptyPageWhenNoPetsFound() {
assertEquals(DEFAULT_PAGE, response.number());
}
}

@Nested
class FindPetTests {
@Test
void shouldReturnPetByIdSuccessfully() {
Pets pet = PetsFixture.builder().build();

when(petRepository.findById(pet.getId())).thenReturn(Optional.of(pet));

PetResponseDTO result = service.find(pet.getId());

assertThat(result.id()).isEqualTo(pet.getId());
assertThat(result.name()).isEqualTo(pet.getName());
}

@Test
void shouldThrowNotFoundExceptionWhenPetDoesNotExist() {
UUID petId = UUID.randomUUID();

when(petRepository.findById(petId)).thenReturn(Optional.empty());

assertThatThrownBy(() -> service.find(petId))
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Pet not found");
}
}
}
Loading