Skip to content

test: add unit tests for PetService#164

Merged
lindaeskilsson merged 6 commits into
mainfrom
test/PetServiceTest
Apr 8, 2026
Merged

test: add unit tests for PetService#164
lindaeskilsson merged 6 commits into
mainfrom
test/PetServiceTest

Conversation

@lindaeskilsson

@lindaeskilsson lindaeskilsson commented Apr 8, 2026

Copy link
Copy Markdown
Contributor

Closes #144

Täcker createPet, getPetById, getPetsByOwner, updatePet och deletePet inklusive behörighetskontroll, felhantering och edge cases som veterinär med/utan klinik och journalåtkomst.

Summary by CodeRabbit

  • Tests
    • Added comprehensive test suite for pet service operations, validating creation, retrieval, updates, and deletion with permission and access control scenarios.

@coderabbitai

coderabbitai Bot commented Apr 8, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

A new JUnit 5 test suite for PetService is introduced using Mockito and AssertJ, with 26 test methods covering creation, retrieval, listing, updating, and deletion operations. Tests validate authorization policies, error handling, and repository interactions across various user roles and edge cases.

Changes

Cohort / File(s) Summary
PetService Test Suite
src/test/java/org/example/vet1177/services/PetServiceTest.java
Comprehensive test coverage for PetService operations: pet creation with owner/admin scenarios and permission validation; pet retrieval by ID with role-based access control (admin, owner, vet); bulk retrieval by owner; updates with authorization checks; deletion with integrity constraint handling. Includes reflection-based helper for private field initialization.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested labels

backend, test

Suggested reviewers

  • johanbriger
  • TatjanaTrajkovic

Poem

🐰 A rabbit hops through test cases bright,
Mocking repos left and right,
PetService now has armor strong,
Permissions checked the whole way long,
With AssertJ's might, bugs take flight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding unit tests for PetService. It is specific, relevant to the changeset, and follows conventional commit format.
Linked Issues check ✅ Passed All coding requirements from issue #144 are met: PetService unit tests comprehensively cover createPet, getPetById, getPetsByOwner, updatePet, and deletePet with proper permission checks, mocked dependencies, and edge case handling.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing unit tests for PetService as specified in issue #144. No extraneous modifications or unrelated changes are present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test/PetServiceTest

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/test/java/org/example/vet1177/services/PetServiceTest.java (2)

35-36: RETURNS_DEEP_STUBS is unnecessary here.

All petRepository interactions in this test class are direct method calls (findById, save, delete, flush), not chained fluent API calls. Deep stubs are typically for patterns like repo.findById().map().orElseThrow(). Using them unnecessarily can obscure missing stubs and return unexpected default values silently.

Suggested fix
-    `@Mock`(answer = org.mockito.Answers.RETURNS_DEEP_STUBS)
-    private PetRepository petRepository;
+    `@Mock`
+    private PetRepository petRepository;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/org/example/vet1177/services/PetServiceTest.java` around lines
35 - 36, The mock declaration in PetServiceTest uses unnecessary deep stubs:
change the annotation on petRepository from `@Mock`(answer =
org.mockito.Answers.RETURNS_DEEP_STUBS) to a plain `@Mock` so interactions with
PetRepository (findById, save, delete, flush) use standard Mockito behavior;
update the PetServiceTest class to remove the answer attribute on the
PetRepository mock and run the tests to ensure no missing stubs or behavior
changes.

217-223: Add explicit stub for existsByPetIdAndClinicId to clarify test intent.

This test relies on Mockito's default return value (false) for medicalRecordRepository.existsByPetIdAndClinicId(). Since the test name explicitly describes "vetWithNoJournalAccess," stubbing this call to return false would make the test self-documenting and resilient to default behavior changes.

Suggested fix
 `@Test`
 void getPetById_vetWithNoJournalAccess_shouldThrowForbiddenException() {
     when(petRepository.findById(petId)).thenReturn(Optional.of(pet));
     when(petPolicy.canView(vet, pet)).thenReturn(false);
+    when(medicalRecordRepository.existsByPetIdAndClinicId(petId, clinic.getId())).thenReturn(false);
+
     assertThatThrownBy(() -> petService.getPetById(petId, vet))
             .isInstanceOf(ForbiddenException.class);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/org/example/vet1177/services/PetServiceTest.java` around lines
217 - 223, Add an explicit Mockito stub for
medicalRecordRepository.existsByPetIdAndClinicId(...) in the test
getPetById_vetWithNoJournalAccess_shouldThrowForbiddenException to return false
so the test intent is clear and not reliant on Mockito defaults; locate the test
method getPetById_vetWithNoJournalAccess_shouldThrowForbiddenException and add a
when(...).thenReturn(false) for
medicalRecordRepository.existsByPetIdAndClinicId(petId, vet.getClinicId())
before invoking petService.getPetById(petId, vet), keeping the existing stubs
for petRepository.findById(...) and petPolicy.canView(...).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/test/java/org/example/vet1177/services/PetServiceTest.java`:
- Around line 35-36: The mock declaration in PetServiceTest uses unnecessary
deep stubs: change the annotation on petRepository from `@Mock`(answer =
org.mockito.Answers.RETURNS_DEEP_STUBS) to a plain `@Mock` so interactions with
PetRepository (findById, save, delete, flush) use standard Mockito behavior;
update the PetServiceTest class to remove the answer attribute on the
PetRepository mock and run the tests to ensure no missing stubs or behavior
changes.
- Around line 217-223: Add an explicit Mockito stub for
medicalRecordRepository.existsByPetIdAndClinicId(...) in the test
getPetById_vetWithNoJournalAccess_shouldThrowForbiddenException to return false
so the test intent is clear and not reliant on Mockito defaults; locate the test
method getPetById_vetWithNoJournalAccess_shouldThrowForbiddenException and add a
when(...).thenReturn(false) for
medicalRecordRepository.existsByPetIdAndClinicId(petId, vet.getClinicId())
before invoking petService.getPetById(petId, vet), keeping the existing stubs
for petRepository.findById(...) and petPolicy.canView(...).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4b4ec61a-e089-4f0d-aff1-87dcfba51c85

📥 Commits

Reviewing files that changed from the base of the PR and between f67dca5 and e15957a.

📒 Files selected for processing (1)
  • src/test/java/org/example/vet1177/services/PetServiceTest.java

@TatjanaTrajkovic TatjanaTrajkovic left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ser bra ut!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test: PetServiceTest – logik och behörighetskontroll

2 participants