Skip to content

test: add unit tests for CommentPolicy and CommentService - #124

Merged
annikaholmqvist94 merged 2 commits into
mainfrom
feat/comment-policy-service-test
Apr 5, 2026
Merged

test: add unit tests for CommentPolicy and CommentService #124
annikaholmqvist94 merged 2 commits into
mainfrom
feat/comment-policy-service-test

Conversation

@annikaholmqvist94

@annikaholmqvist94 annikaholmqvist94 commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Added CommentPolicyTest — 18 tester som täcker alla grenar i canCreate, canView, canUpdate och canDelete, inklusive rollbaserade regler, klinikkontroll och stängda ärenden
  • Added CommentServiceTest — 25 tester med Mockito som täcker create, getByRecord, update, delete och countByRecord; verifierar att policy anropas, att aktivitetslogg skrivs och att
    ResourceNotFoundException kastas vid saknade resurser
  • Fixed pom.xml — ersatte tre icke-existerande test-starters med det korrekta spring-boot-starter-test (inkluderar JUnit 5, AssertJ och Mockito)

Test approach

  • CommentPolicyTest — ren Java, inga mocks, assertThatNoException för happy paths och assertThatThrownBy med exakt meddelande för sad paths
  • CommentServiceTest — @ExtendWith(MockitoExtension.class) utan Spring-kontext, verify() för att bekräfta att policy och loggning anropas, never() för att säkerställa att inget sparas
    vid fel

Closes #97

Summary by CodeRabbit

  • Tests

    • Added comprehensive test suite for comment policy validation covering authorization scenarios, role-based permissions, and access controls.
    • Added comprehensive test suite for comment service operations including create, retrieve, update, delete, and count functionalities.
  • Chores

    • Consolidated test dependency configuration by simplifying Spring Boot test starter declarations.

- Introduced comprehensive unit tests for `CommentPolicy` methods: `canCreate`, `canView`, `canUpdate`, and `canDelete`.
- Simplified test dependencies in `pom.xml` by consolidating into `spring-boot-starter-test`.
- Added comprehensive test coverage for `CommentService` methods: `create`, `getByRecord`, `update`, `delete`, and `countByRecord`.
- Included policy-based validation and activity logging assertions.

Closes #97
- Ensured proper exception handling for missing resources in test cases.
@coderabbitai

coderabbitai Bot commented Apr 4, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This pull request adds comprehensive unit tests for CommentService and CommentPolicy using JUnit 5 and Mockito, verifying authorization rules and business logic. Additionally, Maven test dependencies are consolidated by replacing three separate Spring Boot test starters with a single spring-boot-starter-test dependency.

Changes

Cohort / File(s) Summary
Maven Dependency Consolidation
pom.xml
Replaced three test-scoped Spring Boot starters (spring-boot-starter-data-jpa-test, spring-boot-starter-thymeleaf-test, spring-boot-starter-webmvc-test) with a single spring-boot-starter-test dependency.
Comment Policy Tests
src/test/java/org/example/vet1177/policy/CommentPolicyTest.java
New JUnit 5 test suite validating CommentPolicy authorization logic across four operations: canCreate, canView, canUpdate, canDelete. Tests cover role-based permissions (ADMIN/OWNER/VET), record status restrictions, ownership constraints, and clinic matching rules.
Comment Service Tests
src/test/java/org/example/vet1177/services/CommentServiceTest.java
New JUnit 5 test suite with Mockito mocks validating CommentService business logic. Tests five methods (create, getByRecord, update, delete, countByRecord) covering happy paths, policy enforcement, activity logging, and error handling (ResourceNotFoundException).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

enhancement, testing

Suggested reviewers

  • johanbriger
  • lindaeskilsson
  • TatjanaTrajkovic

Poem

🐰 Hop hop, the tests now hop along,
CommentPolicy strong, authorization's song,
Mocks spring to life, business rules shine,
ADMIN or VET—access so fine!
Dependencies bundled, pom stands tall—
This rabbit approves them all! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 24.39% 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 'test: add unit tests for CommentPolicy and CommentService' clearly and concisely describes the main change—adding unit tests for two specific components.
Linked Issues check ✅ Passed The PR fully addresses all coding requirements from issue #97: CommentServiceTest validates business rules and uses Mockito, CommentPolicyTest validates authorization logic for all CRUD operations, scenarios like edit/delete permissions are covered, and correct exception handling (ResourceNotFoundException) is implemented.
Out of Scope Changes check ✅ Passed All changes are in scope: two test files address #97's requirements, and the pom.xml fix corrects non-existent test starter dependencies with the standard spring-boot-starter-test, which is necessary to support the new tests.

✏️ 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 feat/comment-policy-service-test

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/CommentServiceTest.java (1)

67-106: Add policy-denied path tests to lock down “no side effects on authorization failure”.

Right now the suite validates not-found failures, but not policy rejections. Add explicit tests where commentPolicy throws and assert save/delete/log are not invoked.

✅ Suggested test additions
+    `@Test`
+    void create_whenPolicyDenies_shouldPropagateAndNotSaveOrLog() {
+        when(medicalRecordRepository.findById(recordId)).thenReturn(Optional.of(record));
+        doThrow(new org.example.vet1177.exception.ForbiddenException("Åtkomst nekad"))
+                .when(commentPolicy).canCreate(currentUser, record);
+
+        assertThatThrownBy(() -> commentService.create(recordId, "En kommentar.", currentUser))
+                .isInstanceOf(org.example.vet1177.exception.ForbiddenException.class);
+
+        verify(commentRepository, never()).save(any());
+        verify(activityLogService, never()).log(any(), any(), any(), any());
+    }
+
+    `@Test`
+    void delete_whenPolicyDenies_shouldPropagateAndNotDeleteOrLog() {
+        when(commentRepository.findById(commentId)).thenReturn(Optional.of(comment));
+        doThrow(new org.example.vet1177.exception.ForbiddenException("Åtkomst nekad"))
+                .when(commentPolicy).canDelete(currentUser, comment);
+
+        assertThatThrownBy(() -> commentService.delete(commentId, currentUser))
+                .isInstanceOf(org.example.vet1177.exception.ForbiddenException.class);
+
+        verify(commentRepository, never()).delete(any());
+        verify(activityLogService, never()).log(any(), any(), any(), any());
+    }

Also applies to: 146-226, 232-260

🤖 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/CommentServiceTest.java` around
lines 67 - 106, Add tests that simulate policy denial by making
commentPolicy.canCreate(...) and commentPolicy.canDelete(...) throw the same
authorization exception your service expects, then call
commentService.create(...) and commentService.delete(...). After each call
assert that the service throws the authorization exception and verify
side-effect collaborators are not invoked (verify(commentRepository,
never()).save(...), verify(commentRepository, never()).delete(...),
verify(activityLogService, never()).log(...), etc.). Use the existing test setup
symbols (commentService.create, commentService.delete, commentPolicy.canCreate,
commentPolicy.canDelete, commentRepository, activityLogService) and the same
argument matchers as other tests (any(Comment.class), specific
record/currentUser) so the new tests mirror the existing style.
src/test/java/org/example/vet1177/policy/CommentPolicyTest.java (1)

94-107: Consider extracting repeated user-fixture creation into a helper.

otherOwner / vetNoClinic / other setup repeats the same pattern. A small factory/helper would reduce duplication and future edit churn.

♻️ Example refactor
+    private User newUserWithId(String name, String email, Role role) throws Exception {
+        User user = new User(name, email, "hash", role);
+        setPrivateField(user, "id", UUID.randomUUID());
+        return user;
+    }
+
+    private User newVetWithOptionalClinic(String name, String email, Clinic clinic) throws Exception {
+        User user = (clinic == null)
+                ? new User(name, email, "hash", Role.VET)
+                : new User(name, email, "hash", Role.VET, clinic);
+        setPrivateField(user, "id", UUID.randomUUID());
+        return user;
+    }

Also applies to: 151-164, 198-200, 223-224

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/org/example/vet1177/policy/CommentPolicyTest.java` around lines
94 - 107, Extract the repeated user fixture creation in CommentPolicyTest into a
private helper like buildUser(String name, String email, Role role) (and
optional overload accepting UUID) that constructs new User(...), sets a random
UUID via setPrivateField(..., "id", UUID.randomUUID()) and returns the user;
then replace the inline creations of otherOwner, vetNoClinic, other, etc. in
methods such as canCreate_ownerOnOthersRecord_shouldThrowForbiddenException and
canCreate_vetWithNullUserClinic_shouldThrowForbiddenException with calls to this
helper to remove duplication.
🤖 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/policy/CommentPolicyTest.java`:
- Around line 94-107: Extract the repeated user fixture creation in
CommentPolicyTest into a private helper like buildUser(String name, String
email, Role role) (and optional overload accepting UUID) that constructs new
User(...), sets a random UUID via setPrivateField(..., "id", UUID.randomUUID())
and returns the user; then replace the inline creations of otherOwner,
vetNoClinic, other, etc. in methods such as
canCreate_ownerOnOthersRecord_shouldThrowForbiddenException and
canCreate_vetWithNullUserClinic_shouldThrowForbiddenException with calls to this
helper to remove duplication.

In `@src/test/java/org/example/vet1177/services/CommentServiceTest.java`:
- Around line 67-106: Add tests that simulate policy denial by making
commentPolicy.canCreate(...) and commentPolicy.canDelete(...) throw the same
authorization exception your service expects, then call
commentService.create(...) and commentService.delete(...). After each call
assert that the service throws the authorization exception and verify
side-effect collaborators are not invoked (verify(commentRepository,
never()).save(...), verify(commentRepository, never()).delete(...),
verify(activityLogService, never()).log(...), etc.). Use the existing test setup
symbols (commentService.create, commentService.delete, commentPolicy.canCreate,
commentPolicy.canDelete, commentRepository, activityLogService) and the same
argument matchers as other tests (any(Comment.class), specific
record/currentUser) so the new tests mirror the existing style.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e388291d-2bbd-42b0-8b6b-3a5feb1b6232

📥 Commits

Reviewing files that changed from the base of the PR and between 290f116 and 0a6ac45.

📒 Files selected for processing (3)
  • pom.xml
  • src/test/java/org/example/vet1177/policy/CommentPolicyTest.java
  • src/test/java/org/example/vet1177/services/CommentServiceTest.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 för min del!

@annikaholmqvist94
annikaholmqvist94 merged commit f98cc06 into main Apr 5, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Test: Implement Unit Tests for Comment Service and Authorization Policies

2 participants