feat(tests): add unit tests for Comment entity and DTOs + JaCoCo#123
Conversation
- 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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds JaCoCo Maven plugin to the build and introduces multiple JUnit 5 tests for Comment entity, CommentResponse mapping, and Create/Update comment request validation. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
src/test/java/org/example/vet1177/entities/CommentEntityTest.java (1)
59-78: Duplicate test logic: both tests verifycreatedAtis unchanged afteronUpdate.
onUpdate_shouldRefreshUpdatedAtWithoutModifyingCreatedAt(lines 59-68) already asserts thatcreatedAtremains 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.
getDeclaredFieldandgetDeclaredMethodonly search the declaring class, not superclasses. IfCommentorUserinherits theidfield from a base entity class (common with JPA),setPrivateFieldwill throwNoSuchFieldException.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
📒 Files selected for processing (5)
pom.xmlsrc/test/java/org/example/vet1177/dto/request/comment/CreateCommentRequestValidationTest.javasrc/test/java/org/example/vet1177/dto/request/comment/UpdateCommentRequestValidationTest.javasrc/test/java/org/example/vet1177/dto/response/comment/CommentResponseTest.javasrc/test/java/org/example/vet1177/entities/CommentEntityTest.java
| <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> |
There was a problem hiding this comment.
Missing JaCoCo exclusions and coverage threshold per issue #110 requirements.
The linked issue #110 specifies:
- Configure exclusions for
entities/,dto/,ErrorResponse, andVet1177Applicationmain class. - 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.
| <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.
| <plugin> | ||
| <groupId>org.jacoco</groupId> | ||
| <artifactId>jacoco-maven-plugin</artifactId> | ||
| <version>0.8.14</version> |
There was a problem hiding this comment.
🧩 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).
…red Validator setup and cleanup
Summary
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
Chores