Skip to content

test: add MVC tests for MedicalRecordController#162

Merged
annikaholmqvist94 merged 1 commit into
mainfrom
feat/medical-record-controller-tests
Apr 9, 2026
Merged

test: add MVC tests for MedicalRecordController#162
annikaholmqvist94 merged 1 commit into
mainfrom
feat/medical-record-controller-tests

Conversation

@annikaholmqvist94

@annikaholmqvist94 annikaholmqvist94 commented Apr 8, 2026

Copy link
Copy Markdown
Contributor
  • Introduced MedicalRecordControllerTest with extensive coverage for all endpoints.
  • Verified request/response handling for create, update, assign vet, close, and query operations.
  • Ensured proper exception handling for validation errors, forbidden access, and not found scenarios.Closes Test: Implement Integration Tests for MedicalRecord Controller #101

Summary by CodeRabbit

  • Tests
    • Added comprehensive test coverage for medical record management endpoints, including creation, retrieval, listing with various filters (owner, pet, clinic), record modification, vet assignment, status updates, and authorization enforcement across different user roles and access scenarios.

- Introduced `MedicalRecordControllerTest` with extensive coverage for all endpoints.
- Verified request/response handling for create, update, assign vet, close, and query operations.
- Ensured proper exception handling for validation errors, forbidden access, and not found scenarios.Closes #101
@coderabbitai

coderabbitai Bot commented Apr 8, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

A new Spring MVC slice test class (MedicalRecordControllerTest) is added with 539 lines of test coverage for the MedicalRecordController. The test suite validates all controller endpoints—creation, retrieval, listing, updating, status management, and closing operations—with comprehensive scenarios for success cases, validation failures, authorization denials, and exception handling across multiple user roles.

Changes

Cohort / File(s) Summary
MedicalRecord Controller Tests
src/test/java/org/example/vet1177/controller/MedicalRecordControllerTest.java
New Spring MVC slice test covering POST/PUT/GET endpoints with mocked dependencies, authentication helpers, and comprehensive assertions for success, validation, authorization (role and policy-based), 404/403/400 error responses, and business rule exceptions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • PR #71 — Adds comprehensive unit tests for MedicalRecordController, exercising the same endpoints and mocking identical service/policy dependencies.
  • PR #11 — Implements MedicalRecordService class that is mocked and tested by this controller test suite.

Suggested labels

test

Suggested reviewers

  • johanbriger
  • lindaeskilsson
  • TatjanaTrajkovic

Poem

🐰 A tale of tests so neat and tight,
With mocks and stubs, all shining bright,
Medical records now verified with care,
Role-based access floating through the air,
Five hundred lines of coverage, oh what a sight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.35% 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 MVC tests for MedicalRecordController' directly and clearly summarizes the main change: adding MVC tests for the MedicalRecordController.
Linked Issues check ✅ Passed The PR implements comprehensive MVC tests covering role-based access scenarios (Vet and Patient), all controller endpoints, exception handling, and response validation, fully satisfying issue #101 requirements.
Out of Scope Changes check ✅ Passed All changes are focused on adding test coverage for MedicalRecordController with no modifications to production code or unrelated functionality.

✏️ 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/medical-record-controller-tests

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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/test/java/org/example/vet1177/controller/MedicalRecordControllerTest.java (2)

229-236: Tighten owner-scope assertion by binding to the authenticated owner ID.

Using any(UUID.class) here makes the test pass even if the controller forwards the wrong owner ID. Prefer eq(ownerUser.getId()) (and optionally verify invocation) to lock the access rule behavior.

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

In
`@src/test/java/org/example/vet1177/controller/MedicalRecordControllerTest.java`
around lines 229 - 236, The test getMyRecords_asOwner_shouldReturn200WithList
currently stubs medicalRecordService.getByOwner(any(UUID.class)) which allows
the controller to pass any ID; change the stub to use eq(ownerUser.getId()) so
the service is only invoked for the authenticated owner's UUID (i.e.,
when(medicalRecordService.getByOwner(eq(ownerUser.getId()))). Optionally add a
verify(medicalRecordService).getByOwner(eq(ownerUser.getId())) after the request
to assert the controller forwarded the correct owner ID.

111-125: Strengthen DTO contract checks for success responses.

Current assertions validate selected fields only. To match the payload-contract objective, add assertions for the remaining expected MedicalRecordResponse fields (existence/value/nullability) in representative happy-path tests.

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

In
`@src/test/java/org/example/vet1177/controller/MedicalRecordControllerTest.java`
around lines 111 - 125, In create_shouldReturn200WithMedicalRecordResponse add
JSON assertions to cover the full MedicalRecordResponse contract: assert the
presence and/or expected values for remaining fields from the returned record
(e.g., jsonPath("$.id").exists(), jsonPath("$.description").value("Hostar
mycket"), jsonPath("$.createdAt").isNotEmpty(),
jsonPath("$.updatedAt").value(org.hamcrest.Matchers.nullValue() or expected
value), jsonPath("$.clinicId").value(clinicId),
jsonPath("$.vetId").value(vetUser.getId()), jsonPath("$.petId").value(petId)) so
the test verifies all DTO fields returned by the controller for the happy path;
use the existing record/test fixtures to pick expected values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@src/test/java/org/example/vet1177/controller/MedicalRecordControllerTest.java`:
- Around line 519-527: Update the test close_whenAlreadyClosed_shouldReturn409
to assert a 409 Conflict explicitly: replace the generic
.andExpect(status().is4xxClientError()) assertion on the mockMvc.perform PUT to
/api/medical-records/{id}/close with .andExpect(status().isConflict()), keeping
the same setup of when(medicalRecordService.close(eq(recordId),
any(User.class))).thenThrow(new BusinessRuleException(...)) and the
authenticatedAs(vetUser) request so the test fails if the controller returns any
status other than 409.

---

Nitpick comments:
In
`@src/test/java/org/example/vet1177/controller/MedicalRecordControllerTest.java`:
- Around line 229-236: The test getMyRecords_asOwner_shouldReturn200WithList
currently stubs medicalRecordService.getByOwner(any(UUID.class)) which allows
the controller to pass any ID; change the stub to use eq(ownerUser.getId()) so
the service is only invoked for the authenticated owner's UUID (i.e.,
when(medicalRecordService.getByOwner(eq(ownerUser.getId()))). Optionally add a
verify(medicalRecordService).getByOwner(eq(ownerUser.getId())) after the request
to assert the controller forwarded the correct owner ID.
- Around line 111-125: In create_shouldReturn200WithMedicalRecordResponse add
JSON assertions to cover the full MedicalRecordResponse contract: assert the
presence and/or expected values for remaining fields from the returned record
(e.g., jsonPath("$.id").exists(), jsonPath("$.description").value("Hostar
mycket"), jsonPath("$.createdAt").isNotEmpty(),
jsonPath("$.updatedAt").value(org.hamcrest.Matchers.nullValue() or expected
value), jsonPath("$.clinicId").value(clinicId),
jsonPath("$.vetId").value(vetUser.getId()), jsonPath("$.petId").value(petId)) so
the test verifies all DTO fields returned by the controller for the happy path;
use the existing record/test fixtures to pick expected values.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4f5abbf5-6b43-4579-991d-3848a655d393

📥 Commits

Reviewing files that changed from the base of the PR and between ba13529 and 6dbbd4a.

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

Comment on lines +519 to +527
void close_whenAlreadyClosed_shouldReturn409() throws Exception {
when(medicalRecordService.getById(recordId)).thenReturn(record);
when(medicalRecordService.close(eq(recordId), any(User.class)))
.thenThrow(new BusinessRuleException("Ärendet är redan stängt"));

mockMvc.perform(put("/api/medical-records/{id}/close", recordId)
.with(authenticatedAs(vetUser)))
.andExpect(status().is4xxClientError());
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Make the 409 expectation explicit in the close conflict test.

close_whenAlreadyClosed_shouldReturn409 currently accepts any 4xx on Line 526, which can hide a wrong mapping (e.g., 400/403). Assert 409 Conflict directly.

Suggested change
-                .andExpect(status().is4xxClientError());
+                .andExpect(status().isConflict());
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/test/java/org/example/vet1177/controller/MedicalRecordControllerTest.java`
around lines 519 - 527, Update the test close_whenAlreadyClosed_shouldReturn409
to assert a 409 Conflict explicitly: replace the generic
.andExpect(status().is4xxClientError()) assertion on the mockMvc.perform PUT to
/api/medical-records/{id}/close with .andExpect(status().isConflict()), keeping
the same setup of when(medicalRecordService.close(eq(recordId),
any(User.class))).thenThrow(new BusinessRuleException(...)) and the
authenticatedAs(vetUser) request so the test fails if the controller returns any
status other than 409.

@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!

@annikaholmqvist94
annikaholmqvist94 merged commit df4271c into main Apr 9, 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: Implement Integration Tests for MedicalRecord Controller

3 participants