-
Notifications
You must be signed in to change notification settings - Fork 2
test: add unit tests for PetController #196
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0fea6e0
test: add PetController tests for createPet endpoint
lindaeskilsson 0d98cf1
test: add tests for GET /pets/{petId}
lindaeskilsson 71da4c0
test: add tests for PUT /pets/{petId} and GET /pets/owner/{ownerId}
lindaeskilsson 4c68a68
test: DELETE /pets/{petId}
lindaeskilsson a401a6b
rabbit fixes
lindaeskilsson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
272 changes: 272 additions & 0 deletions
272
src/test/java/org/example/vet1177/controller/PetControllerTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,272 @@ | ||
| package org.example.vet1177.controller; | ||
|
|
||
| //Används i commentControllerTest också, verkar funka där? | ||
| import tools.jackson.databind.ObjectMapper; | ||
| import org.example.vet1177.exception.ResourceNotFoundException; | ||
| import org.example.vet1177.dto.request.pet.PetRequest; | ||
| import org.example.vet1177.entities.Pet; | ||
| import org.example.vet1177.entities.Role; | ||
| import org.example.vet1177.entities.User; | ||
| import org.example.vet1177.exception.ForbiddenException; | ||
| import org.example.vet1177.security.SecurityConfig; | ||
| import org.example.vet1177.services.PetService; | ||
| import org.example.vet1177.services.UserService; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; | ||
| import org.springframework.context.annotation.Import; | ||
| import org.springframework.http.MediaType; | ||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.test.context.bean.override.mockito.MockitoBean; | ||
| import org.springframework.test.web.servlet.MockMvc; | ||
| import org.springframework.test.web.servlet.request.RequestPostProcessor; | ||
|
|
||
| import java.math.BigDecimal; | ||
| import java.time.LocalDate; | ||
| import java.util.List; | ||
| import java.util.UUID; | ||
|
|
||
| import static org.mockito.ArgumentMatchers.any; | ||
| import static org.mockito.Mockito.*; | ||
| import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; | ||
| import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; | ||
| import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; | ||
|
|
||
| @WebMvcTest(PetController.class) | ||
| @Import(SecurityConfig.class) | ||
| public class PetControllerTest { | ||
|
|
||
| @Autowired | ||
| private MockMvc mockMvc; | ||
| @Autowired | ||
| private ObjectMapper objectMapper; | ||
| @MockitoBean | ||
| private PetService petService; | ||
| @MockitoBean | ||
| private UserService userService; | ||
|
|
||
| private User owner; | ||
| private User vet; | ||
| private Pet pet; | ||
| private UUID ownerId; | ||
| private UUID petId; | ||
|
|
||
| @BeforeEach | ||
| void setUp() { | ||
| ownerId = UUID.randomUUID(); | ||
| petId = UUID.randomUUID(); | ||
| owner = new User("Anna Ägare", "anna@mail.se", "hash", Role.OWNER); | ||
| vet = new User("Dr. Erik Vet", "erik@vet.se", "hash", Role.VET); | ||
| pet = new Pet(owner, "Molly", "Hund", "Labrador", LocalDate.of(2020, 1, 1), new BigDecimal("12.50")); | ||
| } | ||
| private RequestPostProcessor authenticatedAs(User user) { | ||
| return authentication(new UsernamePasswordAuthenticationToken( | ||
| user, null, user.getAuthorities() | ||
| )); | ||
| } | ||
|
|
||
| private PetRequest validPetRequest() { | ||
| PetRequest request = new PetRequest(); | ||
| request.setName("Molly"); | ||
| request.setSpecies("Hund"); | ||
| request.setBreed("Labrador"); | ||
| request.setDateOfBirth(LocalDate.of(2020, 1, 1)); | ||
| request.setWeightKg(new BigDecimal("12.50")); | ||
| return request; | ||
| } | ||
|
|
||
| //POST /pets | ||
| @Test | ||
| void createPet_shouldReturn200WithPetResponse() throws Exception { | ||
| when(petService.createPet(any(), any(), any())).thenReturn(pet); | ||
|
|
||
| mockMvc.perform(post("/pets") | ||
| .with(authenticatedAs(owner)) | ||
| .header("currentUserId", ownerId) | ||
| .contentType(MediaType.APPLICATION_JSON) | ||
| .content(objectMapper.writeValueAsString(validPetRequest()))) | ||
| .andExpect(status().isOk()) | ||
| .andExpect(jsonPath("$.name").value("Molly")); | ||
| } | ||
|
|
||
| @Test | ||
| void createPet_whenInvalidRequest_shouldReturn400() throws Exception { | ||
| PetRequest request = validPetRequest(); | ||
| request.setName(""); | ||
|
|
||
| mockMvc.perform(post("/pets") | ||
| .with(authenticatedAs(owner)) | ||
| .header("currentUserId", ownerId) | ||
| .contentType(MediaType.APPLICATION_JSON) | ||
| .content(objectMapper.writeValueAsString(request))) | ||
| .andExpect(status().isBadRequest()); | ||
| } | ||
|
|
||
| @Test | ||
| void createPet_whenForbidden_shouldReturn403() throws Exception { | ||
| when(petService.createPet(any(), any(), any())) | ||
| .thenThrow(new ForbiddenException("Du kan inte lägga till ett djur")); | ||
|
|
||
| mockMvc.perform(post("/pets") | ||
| .with(authenticatedAs(vet)) | ||
| .header("currentUserId", UUID.randomUUID()) | ||
| .contentType(MediaType.APPLICATION_JSON) | ||
| .content(objectMapper.writeValueAsString(validPetRequest()))) | ||
| .andExpect(status().isForbidden()); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| @Test | ||
| void createPet_whenUnexpectedError_shouldReturn500() throws Exception { | ||
| when(petService.createPet(any(), any(), any())) | ||
| .thenThrow(new RuntimeException("Unexpected failure")); | ||
|
|
||
| mockMvc.perform(post("/pets") | ||
| .with(authenticatedAs(owner)) | ||
| .header("currentUserId", ownerId) | ||
| .contentType(MediaType.APPLICATION_JSON) | ||
| .content(objectMapper.writeValueAsString(validPetRequest()))) | ||
| .andExpect(status().isInternalServerError()); | ||
| } | ||
| // GET /pets/{petId} | ||
|
|
||
| @Test | ||
| void getPetById_shouldReturn200WithPetResponse() throws Exception { | ||
| when(userService.getUserEntityById(any())).thenReturn(owner); | ||
| when(petService.getPetById(any(), any())).thenReturn(pet); | ||
|
|
||
| mockMvc.perform(get("/pets/{petId}", petId) | ||
| .with(authenticatedAs(owner)) | ||
| .header("currentUserId", ownerId)) | ||
| .andExpect(status().isOk()) | ||
| .andExpect(jsonPath("$.name").value("Molly")); | ||
| } | ||
|
|
||
| @Test | ||
| void getPetById_whenNotFound_shouldReturn404() throws Exception { | ||
| when(userService.getUserEntityById(any())).thenReturn(owner); | ||
| when(petService.getPetById(any(), any())) | ||
| .thenThrow(new ResourceNotFoundException("Pet", petId)); | ||
|
|
||
| mockMvc.perform(get("/pets/{petId}", petId) | ||
| .with(authenticatedAs(owner)) | ||
| .header("currentUserId", ownerId)) | ||
| .andExpect(status().isNotFound()); | ||
| } | ||
|
|
||
| @Test | ||
| void getPetById_whenForbidden_shouldReturn403() throws Exception { | ||
| when(userService.getUserEntityById(any())).thenReturn(vet); | ||
| when(petService.getPetById(any(), any())) | ||
| .thenThrow(new ForbiddenException("Du har inte behörighet att se detta djur")); | ||
|
|
||
| mockMvc.perform(get("/pets/{petId}", petId) | ||
| .with(authenticatedAs(vet)) | ||
| .header("currentUserId", UUID.randomUUID())) | ||
| .andExpect(status().isForbidden()); | ||
| } | ||
| // GET /pets/owner/{ownerId} | ||
|
|
||
| @Test | ||
| void getPetsByOwner_shouldReturn200WithList() throws Exception { | ||
| when(petService.getPetsByOwner(any(), any())).thenReturn(List.of(pet)); | ||
|
|
||
| mockMvc.perform(get("/pets/owner/{ownerId}", ownerId) | ||
| .with(authenticatedAs(owner)) | ||
| .header("currentUserId", ownerId)) | ||
| .andExpect(status().isOk()) | ||
| .andExpect(jsonPath("$[0].name").value("Molly")); | ||
| } | ||
|
|
||
| @Test | ||
| void getPetsByOwner_whenForbidden_shouldReturn403() throws Exception { | ||
| when(petService.getPetsByOwner(any(), any())) | ||
| .thenThrow(new ForbiddenException("Du saknar behörighet")); | ||
|
|
||
| mockMvc.perform(get("/pets/owner/{ownerId}", ownerId) | ||
| .with(authenticatedAs(vet)) | ||
| .header("currentUserId", UUID.randomUUID())) | ||
| .andExpect(status().isForbidden()); | ||
| } | ||
|
|
||
| // PUT /pets/{petId} | ||
|
|
||
| @Test | ||
| void updatePet_shouldReturn200WithUpdatedPetResponse() throws Exception { | ||
| Pet updated = new Pet(owner, "Harry", "Katt", "Siamese", LocalDate.of(2021, 3, 5), new BigDecimal("5.00")); | ||
| when(petService.updatePet(any(), any(), any())).thenReturn(updated); | ||
|
|
||
| mockMvc.perform(put("/pets/{petId}", petId) | ||
| .with(authenticatedAs(owner)) | ||
| .header("currentUserId", ownerId) | ||
| .contentType(MediaType.APPLICATION_JSON) | ||
| .content(objectMapper.writeValueAsString(validPetRequest()))) | ||
| .andExpect(status().isOk()) | ||
| .andExpect(jsonPath("$.name").value("Harry")); | ||
| } | ||
|
|
||
| @Test | ||
| void updatePet_whenNotFound_shouldReturn404() throws Exception { | ||
| when(petService.updatePet(any(), any(), any())) | ||
| .thenThrow(new ResourceNotFoundException("Pet", petId)); | ||
|
|
||
| mockMvc.perform(put("/pets/{petId}", petId) | ||
| .with(authenticatedAs(owner)) | ||
| .header("currentUserId", ownerId) | ||
| .contentType(MediaType.APPLICATION_JSON) | ||
| .content(objectMapper.writeValueAsString(validPetRequest()))) | ||
| .andExpect(status().isNotFound()); | ||
| } | ||
|
|
||
| @Test | ||
| void updatePet_whenForbidden_shouldReturn403() throws Exception { | ||
| when(petService.updatePet(any(), any(), any())) | ||
| .thenThrow(new ForbiddenException("Du saknar behörighet")); | ||
|
|
||
| mockMvc.perform(put("/pets/{petId}", petId) | ||
| .with(authenticatedAs(vet)) | ||
| .header("currentUserId", UUID.randomUUID()) | ||
| .contentType(MediaType.APPLICATION_JSON) | ||
| .content(objectMapper.writeValueAsString(validPetRequest()))) | ||
| .andExpect(status().isForbidden()); | ||
| } | ||
|
|
||
| //DELETE /pets/{petId} | ||
|
|
||
|
|
||
| @Test | ||
| void deletePet_shouldReturn204() throws Exception { | ||
| when(userService.getUserEntityById(any())).thenReturn(owner); | ||
| doNothing().when(petService).deletePet(any(), any()); | ||
|
|
||
| mockMvc.perform(delete("/pets/{petId}", petId) | ||
| .with(authenticatedAs(owner)) | ||
| .header("currentUserId", ownerId)) | ||
| .andExpect(status().isNoContent()); | ||
| } | ||
|
|
||
| @Test | ||
| void deletePet_whenNotFound_shouldReturn404() throws Exception { | ||
| when(userService.getUserEntityById(any())).thenReturn(owner); | ||
| doThrow(new ResourceNotFoundException("Pet", petId)) | ||
| .when(petService).deletePet(any(), any()); | ||
|
|
||
| mockMvc.perform(delete("/pets/{petId}", petId) | ||
| .with(authenticatedAs(owner)) | ||
| .header("currentUserId", ownerId)) | ||
| .andExpect(status().isNotFound()); | ||
| } | ||
|
|
||
| @Test | ||
| void deletePet_whenForbidden_shouldReturn403() throws Exception { | ||
| when(userService.getUserEntityById(any())).thenReturn(vet); | ||
| doThrow(new ForbiddenException("Du har inte behörighet att radera detta djur")) | ||
| .when(petService).deletePet(any(), any()); | ||
|
|
||
| mockMvc.perform(delete("/pets/{petId}", petId) | ||
| .with(authenticatedAs(vet)) | ||
| .header("currentUserId", UUID.randomUUID())) | ||
| .andExpect(status().isForbidden()); | ||
| } | ||
|
|
||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.