Skip to content

Test: add unit tests for VetService (business logic and error handling)#185

Merged
TatjanaTrajkovic merged 1 commit into
mainfrom
test/unit_tests_vet_service
Apr 10, 2026
Merged

Test: add unit tests for VetService (business logic and error handling)#185
TatjanaTrajkovic merged 1 commit into
mainfrom
test/unit_tests_vet_service

Conversation

@TatjanaTrajkovic

@TatjanaTrajkovic TatjanaTrajkovic commented Apr 9, 2026

Copy link
Copy Markdown
Contributor
  • Added unit tests for createVet covering:

    • successful creation
    • user not found
    • duplicate licenseId
    • user already registered as vet
    • Verified role update from OWNER to VET during vet creation
    • Added tests for getAllVets and getVetById
    • Replaced mocked entities with real objects to support DTO mapping
    • Ensured proper exception handling with ResourceNotFoundException and BusinessRuleException
    • Used Mockito for repository mocking and interaction verification

Summary by CodeRabbit

  • Tests
    • Added comprehensive test coverage for veterinarian service operations, including creation, retrieval, and error handling scenarios.

* Added unit tests for createVet covering:

  * successful creation
  * user not found
  * duplicate licenseId
  * user already registered as vet
  * Verified role update from OWNER to VET during vet creation
  * Added tests for getAllVets and getVetById
  * Replaced mocked entities with real objects to support DTO mapping
  * Ensured proper exception handling with ResourceNotFoundException and BusinessRuleException
  * Used Mockito for repository mocking and interaction verification
@coderabbitai

coderabbitai Bot commented Apr 9, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Added a new JUnit 5 test class VetServiceTest with comprehensive test coverage for VetService, including tests for createVet, getAllVets, and getVetById methods. Tests verify successful creation flows, role updates, and handle error cases such as missing users, duplicate license IDs, and existing vets.

Changes

Cohort / File(s) Summary
VetService Unit Tests
src/test/java/org/example/vet1177/services/VetServiceTest.java
New JUnit 5 test class with 7 test methods covering createVet success/failure scenarios (user not found, duplicate license, user already vet), getAllVets retrieval, and getVetById with not-found handling. Uses Mockito for mocking repository dependencies.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

  • Issue #168: Directly addresses adding the same unit test coverage for VetService, including createVet, getAllVets, getVetById and identical success/error test cases.

Possibly related PRs

  • PR #10: The test suite mocks VetRepository methods (existsByLicenseId, findById, findAll, save) that are defined in this PR.
  • PR #67: The new tests directly exercise VetService.createVet, getAllVets, and getVetById methods implemented in this PR.

Suggested reviewers

  • annikaholmqvist94
  • johanbriger

Poem

🐰 A vet's service tested, neat and true,
Seven methods checked with mocks brand new,
Success and failures, both have their place,
Unit tests hop with methodical grace! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: adding unit tests for VetService with focus on business logic and error handling, which aligns with the changeset.

✏️ 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/unit_tests_vet_service

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/VetServiceTest.java (2)

122-169: Consider extracting shared fixtures for User/Vet.

User and Vet setup is duplicated across retrieval tests; small builders/helpers would reduce noise and future edit cost.

Example refactor
+    private User buildActiveUser(String name, String email) {
+        User user = new User();
+        user.setName(name);
+        user.setEmail(email);
+        user.setActive(true);
+        return user;
+    }
+
+    private Vet buildVet(User user, String licenseId) {
+        Vet vet = new Vet();
+        vet.setUser(user);
+        vet.setLicenseId(licenseId);
+        return vet;
+    }
🤖 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/VetServiceTest.java` around lines
122 - 169, Extract the duplicated User/Vet setup in VetServiceTest into small
private factory/helper methods (e.g., private User makeUser(String name, String
email, boolean active) and private Vet makeVet(User user, String licenseId)) and
update tests should_return_all_vets and should_return_vet_by_id to call these
helpers instead of duplicating object creation; ensure the helpers set the same
fields currently used in tests (name/email/active on User and user/licenseId on
Vet) and keep existing mock interactions (when(vetRepository.findAll())... and
when(vetRepository.findById(id))... ) and assertions unchanged.

39-116: Good createVet coverage overall; one branch is still missing.

You covered success + key business-rule failures well. The remaining gap is the repository-save failure path in createVet that should still surface as BusinessRuleException.

Add a focused test for the save-failure translation path
+    `@Test`
+    void should_throw_business_rule_when_persistence_fails_on_save() {
+        UUID userId = UUID.randomUUID();
+        User user = new User();
+        user.setRole(Role.OWNER);
+
+        VetRequest request = new VetRequest(userId, "LIC123", "Surgery", "Info");
+
+        when(userRepository.findById(userId)).thenReturn(Optional.of(user));
+        when(vetRepository.existsByLicenseId("LIC123")).thenReturn(false);
+        when(vetRepository.existsById(userId)).thenReturn(false);
+        when(vetRepository.save(any(Vet.class)))
+                .thenThrow(new org.springframework.dao.DataIntegrityViolationException("constraint"));
+
+        assertThrows(BusinessRuleException.class, () -> vetService.createVet(request));
+    }
🤖 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/VetServiceTest.java` around lines
39 - 116, Add a unit test in VetServiceTest that covers the repo-save failure
path: arrange a valid User (role OWNER) and a VetRequest, mock
userRepository.findById(...) to return the user, mock
vetRepository.existsByLicenseId(...) and existsById(...) to return false, then
stub vetRepository.save(...) to throw a RuntimeException (or generic exception)
and assert that calling vetService.createVet(request) throws
BusinessRuleException; reference createVet, vetRepository.save, and
BusinessRuleException to locate the code under test.
🤖 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/VetServiceTest.java`:
- Around line 122-169: Extract the duplicated User/Vet setup in VetServiceTest
into small private factory/helper methods (e.g., private User makeUser(String
name, String email, boolean active) and private Vet makeVet(User user, String
licenseId)) and update tests should_return_all_vets and should_return_vet_by_id
to call these helpers instead of duplicating object creation; ensure the helpers
set the same fields currently used in tests (name/email/active on User and
user/licenseId on Vet) and keep existing mock interactions
(when(vetRepository.findAll())... and when(vetRepository.findById(id))... ) and
assertions unchanged.
- Around line 39-116: Add a unit test in VetServiceTest that covers the
repo-save failure path: arrange a valid User (role OWNER) and a VetRequest, mock
userRepository.findById(...) to return the user, mock
vetRepository.existsByLicenseId(...) and existsById(...) to return false, then
stub vetRepository.save(...) to throw a RuntimeException (or generic exception)
and assert that calling vetService.createVet(request) throws
BusinessRuleException; reference createVet, vetRepository.save, and
BusinessRuleException to locate the code under test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9ab44342-a053-43eb-9ef1-942d923258b1

📥 Commits

Reviewing files that changed from the base of the PR and between 5a74e27 and 3188f37.

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

@TatjanaTrajkovic
TatjanaTrajkovic merged commit 80cb8f8 into main Apr 10, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Test: Add unit tests for VetService (business logic and error handling)

1 participant