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
16 changes: 16 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 @@ -15,6 +15,7 @@
import java.util.UUID;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
Expand Down Expand Up @@ -91,6 +92,21 @@ public interface PetsController {
ResponseEntity<PetResponseDTO> update(
@PathVariable UUID id, @Valid @RequestBody PetRequestDTO dto);

@Operation(summary = "Deletar pet", description = "Deletar um pet pelo seu id")
@ApiResponse(responseCode = "204", description = "Pet deletado com sucesso")
@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\"]}")))
@DeleteMapping("/{id}")
ResponseEntity<Void> delete(@PathVariable UUID id);

@Operation(summary = "Buscar pets", description = "Retorna uma lista paginada de pets")
@ApiResponse(
responseCode = "200",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ public ResponseEntity<PetResponseDTO> update(UUID id, PetRequestDTO dto) {
return ResponseEntity.status(HttpStatus.OK).body(response);
}

@Override
public ResponseEntity<Void> delete(UUID id) {
petsService.delete(id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}

@Override
public ResponseEntity<PageResponseDTO<PetResponseDTO>> findAll(PageableRequestDTO pageable) {
PageResponseDTO<PetResponseDTO> response = petsService.findAll(pageable);
Expand Down
2 changes: 2 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 @@ -11,6 +11,8 @@ public interface PetsService {

PetResponseDTO update(UUID id, PetRequestDTO dto);

void delete(UUID id);

PageResponseDTO<PetResponseDTO> findAll(PageableRequestDTO pageable);

PetResponseDTO find(UUID id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ public PetResponseDTO update(UUID id, PetRequestDTO dto) {
return petsMapper.toResponse(updatedPet);
}

@Override
@Transactional
public void delete(UUID id) {
Pets pet = findPet(id);
petRepository.delete(pet);
}

@Override
public PageResponseDTO<PetResponseDTO> findAll(PageableRequestDTO pageable) {
Page<PetResponseDTO> page =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
ALTER TABLE tb_pet_tags
DROP CONSTRAINT IF EXISTS fk_pet_id;

ALTER TABLE tb_pet_tags
ADD CONSTRAINT fk_pet_id
FOREIGN KEY (pet_id)
REFERENCES tb_pets(id)
ON DELETE CASCADE;
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
Expand Down Expand Up @@ -259,8 +262,6 @@ void shouldUpdatePetSuccessfully() throws Exception {
.content(JsonUtils.convertToJson(request)))
.andExpect(status().isOk())
.andExpect(content().json(JsonUtils.convertToJson(response)));

verify(petsService).update(petId, request);
}

@Test
Expand Down Expand Up @@ -304,4 +305,32 @@ static Stream<PetRequestDTO> invalidPetRequestsProvider() {
PetsFixture.requestDtoBuilder().status(null).build());
}
}

@Nested
class DeletePetTests {
@Test
void shouldDeletePetSuccessfully() throws Exception {
UUID petId = UUID.randomUUID();

doNothing().when(petsService).delete(petId);

mockMvc
.perform(delete(PET_ID_URL, petId).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent())
.andExpect(content().string(""));
}

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

doThrow(new NotFoundException(errorMessage)).when(petsService).delete(invalidId);

mockMvc
.perform(delete(PET_ID_URL, invalidId).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.messages[0]").value(errorMessage));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,21 @@ void shouldUpdatePetSuccessfully() {
}
}

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

ResponseEntity<Void> response =
restTemplate.exchange(PET_ID_URL, HttpMethod.DELETE, null, Void.class, savedPet.getId());

assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
assertThat(petsRepository.findById(savedPet.getId())).isEmpty();
}
}

public Pets.PetsBuilder builderWithoutId() {
return PetsFixture.builder().id(null).species(savedSpecies);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -409,4 +409,31 @@ void shouldThrowNotFoundExceptionWhenTagDoesNotExist() {
verify(petRepository, never()).saveAndFlush(any());
}
}

@Nested
class DeletePetTests {
@Test
void shouldDeletePetSuccessfully() {
Pets existingPet = PetsFixture.builder().build();

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

service.delete(existingPet.getId());

verify(petRepository, times(1)).delete(existingPet);
}

@Test
void shouldReturnNotFoundWhenDeletingNonexistentPet() {
UUID invalidId = UUID.randomUUID();

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

assertThatThrownBy(() -> service.delete(invalidId))
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Pet not found");

verify(petRepository, never()).delete(any());
}
}
}
Loading