Skip to content

feat(tests): add unit tests for Comment entity and DTOs + JaCoCo#123

Merged
annikaholmqvist94 merged 6 commits into
mainfrom
feat/comment-entity-and-dtos-test
Apr 5, 2026
Merged

feat(tests): add unit tests for Comment entity and DTOs + JaCoCo#123
annikaholmqvist94 merged 6 commits into
mainfrom
feat/comment-entity-and-dtos-test

Conversation

@annikaholmqvist94

@annikaholmqvist94 annikaholmqvist94 commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Added unit tests for CommentEntity covering getters/setters, lifecycle methods (onCreate, onUpdate) and null defaults before persist
  • Added unit tests for CommentResponse covering field mapping from entity, timestamp consistency and null-throws for author and medicalRecord
  • Added validation tests for CreateCommentRequest and UpdateCommentRequest covering happy paths, blank/null/too-long body and null recordId
  • Introduced JaCoCo Maven plugin for code coverage reporting (mvn verify → target/site/jacoco/index.html)

Test approach

All tests use JUnit 5 + AssertJ and follow the happy path / sad path structure.

Closes

Closes #110
Closes #96

Summary by CodeRabbit

  • Tests

    • Added comprehensive tests for comment request validation (required fields and 5,000-char limits), comment response mapping, and comment entity lifecycle (creation and update behaviors).
  • Chores

    • Enabled code coverage collection and automated report generation in the build to improve quality visibility.

- Introduced comprehensive unit tests for `Comment` entity covering:
  - Getters and setters for all fields.
  - Lifecycle methods (`onCreate` and `onUpdate`).
  - Null-value validations prior to persistence.
- Added comprehensive unit tests for `CommentResponse` covering:
  - Field mapping from `Comment` entity.
  - Validation of null cases for `author` and `medicalRecord`.
  - Timestamps (`createdAt`, `updatedAt`) consistency checks.
- Introduced JaCoCo Maven plugin for code coverage reporting.
- Removed redundant `onCreate_createdAtAndUpdatedAtShouldBeEqual` test from `CommentEntityTest`.
…uest`

- Introduced unit tests to validate fields and constraints in `CreateCommentRequest` and `UpdateCommentRequest`.
- Covered both valid and invalid scenarios for request bodies and identifiers.
…uest`

- Introduced unit tests to validate fields and constraints in `CreateCommentRequest` and `UpdateCommentRequest`.
- Covered both valid and invalid scenarios for request bodies and identifiers.

Closes #110
Closes #96
@coderabbitai

coderabbitai Bot commented Apr 4, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4f070df9-31de-4783-9078-5da69775daa1

📥 Commits

Reviewing files that changed from the base of the PR and between c2b3cae and 7f34af5.

📒 Files selected for processing (2)
  • src/test/java/org/example/vet1177/dto/request/comment/CreateCommentRequestValidationTest.java
  • src/test/java/org/example/vet1177/dto/request/comment/UpdateCommentRequestValidationTest.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/test/java/org/example/vet1177/dto/request/comment/CreateCommentRequestValidationTest.java
  • src/test/java/org/example/vet1177/dto/request/comment/UpdateCommentRequestValidationTest.java

📝 Walkthrough

Walkthrough

Adds JaCoCo Maven plugin to the build and introduces multiple JUnit 5 tests for Comment entity, CommentResponse mapping, and Create/Update comment request validation.

Changes

Cohort / File(s) Summary
JaCoCo Coverage Configuration
pom.xml
Added org.jacoco:jacoco-maven-plugin (v0.8.14) with executions: prepare-agent, report bound to prepare-package, and a report execution bound to test specifying dataFile=target/jacoco.exec and outputDirectory=target/jacoco-ut. Minor whitespace adjustments.
Comment Entity Tests
src/test/java/.../entities/CommentEntityTest.java
New tests for Comment verifying getters/setters, identity of referenced User/MedicalRecord, lifecycle methods onCreate()/onUpdate(), and default null state before lifecycle.
Comment Response Mapping Tests
src/test/java/.../dto/response/comment/CommentResponseTest.java
New tests for CommentResponse.from(comment) validating mapped fields (id, recordId, authorId, authorName, body, timestamps) and asserting NPE when author or medicalRecord is null. Uses reflection helpers for private/protected members.
Comment Request DTO Validation Tests
src/test/java/.../dto/request/comment/CreateCommentRequestValidationTest.java, src/test/java/.../dto/request/comment/UpdateCommentRequestValidationTest.java
New Jakarta Bean Validation tests for CreateCommentRequest and UpdateCommentRequest: happy-path and multiple sad-path cases (null/blank/empty/oversized bodies, null recordId), asserting violation counts and exact Swedish messages; sets up ValidatorFactory/Validator lifecycle.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • johanbriger
  • TatjanaTrajkovic
  • lindaeskilsson

Poem

🐰
Hop, I set the coverage free,
Tests nibble at each boundary,
Comments mapped and validated true,
JaCoCo counts every hop I do,
Tail twitch — build green, huzzah!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% 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 accurately summarizes the main changes: adding unit tests for Comment entity and DTOs plus JaCoCo configuration.
Linked Issues check ✅ Passed The PR addresses both #110 (JaCoCo plugin added to pom.xml) and #96 (comprehensive unit tests for Comment entity, DTOs, and validation).
Out of Scope Changes check ✅ Passed All changes align with the objectives: JaCoCo plugin configuration, and unit tests for Comment entity and DTOs.

✏️ 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-entity-and-dtos-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.

Actionable comments posted: 4

🧹 Nitpick comments (2)
src/test/java/org/example/vet1177/entities/CommentEntityTest.java (1)

59-78: Duplicate test logic: both tests verify createdAt is unchanged after onUpdate.

onUpdate_shouldRefreshUpdatedAtWithoutModifyingCreatedAt (lines 59-68) already asserts that createdAt remains equal to the original value. onUpdate_shouldNotModifyCreatedAt (lines 70-78) duplicates this assertion.

Consider removing the redundant test or consolidating them.

Remove redundant test
-    `@Test`
-    void onUpdate_shouldNotModifyCreatedAt() {
-        comment.onCreate();
-        Instant originalCreatedAt = comment.getCreatedAt();
-
-        comment.onUpdate();
-
-        assertThat(comment.getCreatedAt()).isEqualTo(originalCreatedAt);
-    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/org/example/vet1177/entities/CommentEntityTest.java` around
lines 59 - 78, The test suite contains duplicate logic: both test methods
onUpdate_shouldRefreshUpdatedAtWithoutModifyingCreatedAt and
onUpdate_shouldNotModifyCreatedAt in CommentEntityTest assert that
comment.getCreatedAt() is unchanged after calling comment.onUpdate(); remove the
redundant onUpdate_shouldNotModifyCreatedAt test (or merge its unique assertions
into the first test), keeping the test that verifies both that getUpdatedAt() is
refreshed and getCreatedAt() remains equal to the original value after calling
comment.onUpdate() (using comment.onCreate(), comment.onUpdate(),
comment.getCreatedAt(), and comment.getUpdatedAt()) so behavior is covered once.
src/test/java/org/example/vet1177/dto/response/comment/CommentResponseTest.java (1)

98-108: Reflection helpers may fail for inherited fields/methods.

getDeclaredField and getDeclaredMethod only search the declaring class, not superclasses. If Comment or User inherits the id field from a base entity class (common with JPA), setPrivateField will throw NoSuchFieldException.

Proposed fix: traverse class hierarchy
     private static void setPrivateField(Object target, String fieldName, Object value) throws Exception {
-        Field field = target.getClass().getDeclaredField(fieldName);
+        Field field = findField(target.getClass(), fieldName);
         field.setAccessible(true);
         field.set(target, value);
     }
+
+    private static Field findField(Class<?> clazz, String fieldName) throws NoSuchFieldException {
+        while (clazz != null) {
+            try {
+                return clazz.getDeclaredField(fieldName);
+            } catch (NoSuchFieldException e) {
+                clazz = clazz.getSuperclass();
+            }
+        }
+        throw new NoSuchFieldException(fieldName);
+    }

Alternatively, consider using Spring's ReflectionTestUtils.setField() which handles this automatically.

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

In
`@src/test/java/org/example/vet1177/dto/response/comment/CommentResponseTest.java`
around lines 98 - 108, The helper methods setPrivateField and
callProtectedMethod use getDeclaredField/getDeclaredMethod which only search the
target's declaring class and will throw
NoSuchFieldException/NoSuchMethodException for inherited members; update both
helpers to traverse the class hierarchy (walk target.getClass() ->
getSuperclass() until Object) to find the Field/Method, set it accessible, and
then set/invoke it, or replace their usage with Spring's
ReflectionTestUtils.setField()/invokeMethod() to handle inherited members
automatically; ensure you still handle and rethrow reflection exceptions
consistently in setPrivateField and callProtectedMethod.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pom.xml`:
- Line 102: The JaCoCo plugin version declared as <version>0.8.14</version> in
the pom.xml is invalid on Maven Central; update that <version> element for the
JaCoCo plugin to a published release (e.g., 0.8.13) so the build can resolve the
dependency; locate the JaCoCo plugin declaration in pom.xml and change the
<version> value from 0.8.14 to 0.8.13 (or another known-good released version).
- Around line 99-129: Update the org.jacoco:jacoco-maven-plugin configuration to
add exclusions and a coverage check: inside the plugin's <executions> add or
modify the report execution to include <configuration><excludes> patterns for
/**/entities/**, /**/dto/**, **/ErrorResponse*, and **/Vet1177Application* (to
exclude those classes/packages from reports), and add a new execution (or
augment existing) with goal "check" that runs in the verify phase and contains a
<rules> block enforcing a minimum instruction/line/branch coverage of 60%
(violation rules -> limit -> minimum 0.60) so the build fails if coverage drops
below 60%. Ensure these changes target the jacoco-maven-plugin configuration
(executions/report and executions/check) so exclusions and the 60% threshold are
enforced.

In
`@src/test/java/org/example/vet1177/dto/request/comment/CreateCommentRequestValidationTest.java`:
- Around line 19-24: The setUp method closes the ValidatorFactory in the
try-with-resources block causing the Validator to be used after its factory is
closed; change to initialize a static ValidatorFactory and Validator in a
`@BeforeAll` static method (or store the factory as a class-level field) and close
the factory in an `@AfterAll` static method so the factory remains open while
tests run; reference the CreateCommentRequestValidationTest class, its setUp
method, the ValidatorFactory and validator variables, and add imports for
org.junit.jupiter.api.BeforeAll and org.junit.jupiter.api.AfterAll as suggested.

In
`@src/test/java/org/example/vet1177/dto/request/comment/UpdateCommentRequestValidationTest.java`:
- Around line 18-23: The setUp() method currently closes the ValidatorFactory
immediately (try-with-resources) but stores a Validator used later, which is
undefined behavior; change lifecycle to keep the factory open for the test
class: create the ValidatorFactory and Validator in `@BeforeAll` (e.g., call
Validation.buildDefaultValidatorFactory() and assign to a class-level factory
field, then getValidator() into the class-level validator field) and close the
factory in an `@AfterAll` method; update annotations from `@BeforeEach` to
`@BeforeAll` on the initializer and add an `@AfterAll` tearDown that calls
factory.close() so Validator is used while its factory remains open (refer to
setUp(), validator, ValidatorFactory, and
Validation.buildDefaultValidatorFactory()).

---

Nitpick comments:
In
`@src/test/java/org/example/vet1177/dto/response/comment/CommentResponseTest.java`:
- Around line 98-108: The helper methods setPrivateField and callProtectedMethod
use getDeclaredField/getDeclaredMethod which only search the target's declaring
class and will throw NoSuchFieldException/NoSuchMethodException for inherited
members; update both helpers to traverse the class hierarchy (walk
target.getClass() -> getSuperclass() until Object) to find the Field/Method, set
it accessible, and then set/invoke it, or replace their usage with Spring's
ReflectionTestUtils.setField()/invokeMethod() to handle inherited members
automatically; ensure you still handle and rethrow reflection exceptions
consistently in setPrivateField and callProtectedMethod.

In `@src/test/java/org/example/vet1177/entities/CommentEntityTest.java`:
- Around line 59-78: The test suite contains duplicate logic: both test methods
onUpdate_shouldRefreshUpdatedAtWithoutModifyingCreatedAt and
onUpdate_shouldNotModifyCreatedAt in CommentEntityTest assert that
comment.getCreatedAt() is unchanged after calling comment.onUpdate(); remove the
redundant onUpdate_shouldNotModifyCreatedAt test (or merge its unique assertions
into the first test), keeping the test that verifies both that getUpdatedAt() is
refreshed and getCreatedAt() remains equal to the original value after calling
comment.onUpdate() (using comment.onCreate(), comment.onUpdate(),
comment.getCreatedAt(), and comment.getUpdatedAt()) so behavior is covered once.
🪄 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: e383f343-c48f-40d1-b2b3-cd6340006ec7

📥 Commits

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

📒 Files selected for processing (5)
  • pom.xml
  • src/test/java/org/example/vet1177/dto/request/comment/CreateCommentRequestValidationTest.java
  • src/test/java/org/example/vet1177/dto/request/comment/UpdateCommentRequestValidationTest.java
  • src/test/java/org/example/vet1177/dto/response/comment/CommentResponseTest.java
  • src/test/java/org/example/vet1177/entities/CommentEntityTest.java

Comment thread pom.xml
Comment on lines +99 to +129
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.14</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>target/jacoco.exec</dataFile>
<outputDirectory>target/jacoco-ut</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>

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

Missing JaCoCo exclusions and coverage threshold per issue #110 requirements.

The linked issue #110 specifies:

  1. Configure exclusions for entities/, dto/, ErrorResponse, and Vet1177Application main class.
  2. Set a minimum coverage threshold of 60%.

Currently, the plugin only configures report generation without exclusions or enforcement.

Proposed fix to add exclusions and coverage check
             <plugin>
                 <groupId>org.jacoco</groupId>
                 <artifactId>jacoco-maven-plugin</artifactId>
                 <version>0.8.14</version>
+                <configuration>
+                    <excludes>
+                        <exclude>**/entities/**</exclude>
+                        <exclude>**/dto/**</exclude>
+                        <exclude>**/ErrorResponse.*</exclude>
+                        <exclude>**/Vet1177Application.*</exclude>
+                    </excludes>
+                </configuration>
                 <executions>
                     <execution>
                         <id>prepare-agent</id>
                         <goals>
                             <goal>prepare-agent</goal>
                         </goals>
                     </execution>
                     <execution>
                         <id>report</id>
                         <phase>prepare-package</phase>
                         <goals>
                             <goal>report</goal>
                         </goals>
                     </execution>
                     <execution>
                         <id>post-unit-test</id>
                         <phase>test</phase>
                         <goals>
                             <goal>report</goal>
                         </goals>
                         <configuration>
                             <dataFile>target/jacoco.exec</dataFile>
                             <outputDirectory>target/jacoco-ut</outputDirectory>
                         </configuration>
                     </execution>
+                    <execution>
+                        <id>check</id>
+                        <goals>
+                            <goal>check</goal>
+                        </goals>
+                        <configuration>
+                            <rules>
+                                <rule>
+                                    <element>BUNDLE</element>
+                                    <limits>
+                                        <limit>
+                                            <counter>LINE</counter>
+                                            <value>COVEREDRATIO</value>
+                                            <minimum>0.60</minimum>
+                                        </limit>
+                                    </limits>
+                                </rule>
+                            </rules>
+                        </configuration>
+                    </execution>
                 </executions>
             </plugin>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.14</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>target/jacoco.exec</dataFile>
<outputDirectory>target/jacoco-ut</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.14</version>
<configuration>
<excludes>
<exclude>**/entities/**</exclude>
<exclude>**/dto/**</exclude>
<exclude>**/ErrorResponse.*</exclude>
<exclude>**/Vet1177Application.*</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>target/jacoco.exec</dataFile>
<outputDirectory>target/jacoco-ut</outputDirectory>
</configuration>
</execution>
<execution>
<id>check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>BUNDLE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.60</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pom.xml` around lines 99 - 129, Update the org.jacoco:jacoco-maven-plugin
configuration to add exclusions and a coverage check: inside the plugin's
<executions> add or modify the report execution to include
<configuration><excludes> patterns for /**/entities/**, /**/dto/**,
**/ErrorResponse*, and **/Vet1177Application* (to exclude those classes/packages
from reports), and add a new execution (or augment existing) with goal "check"
that runs in the verify phase and contains a <rules> block enforcing a minimum
instruction/line/branch coverage of 60% (violation rules -> limit -> minimum
0.60) so the build fails if coverage drops below 60%. Ensure these changes
target the jacoco-maven-plugin configuration (executions/report and
executions/check) so exclusions and the 60% threshold are enforced.

Comment thread pom.xml
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.14</version>

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 | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if JaCoCo 0.8.14 is available on Maven Central
curl -s "https://search.maven.org/solrsearch/select?q=g:org.jacoco+AND+a:jacoco-maven-plugin&rows=5&wt=json" | jq '.response.docs[] | {latestVersion, timestamp}'

Repository: ithsjava25/project-backend-org-random-coders

Length of output: 149


JaCoCo version 0.8.14 does not exist on Maven Central. The latest available version is 0.8.13. Update the plugin version to 0.8.13 or another available release.

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

In `@pom.xml` at line 102, The JaCoCo plugin version declared as
<version>0.8.14</version> in the pom.xml is invalid on Maven Central; update
that <version> element for the JaCoCo plugin to a published release (e.g.,
0.8.13) so the build can resolve the dependency; locate the JaCoCo plugin
declaration in pom.xml and change the <version> value from 0.8.14 to 0.8.13 (or
another known-good released version).

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

Labels

enhancement New feature or request test

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: add JaCoCo test coverage reporting Test: Implement Unit Tests for Comment Entity and DTOs

1 participant