Skip to content

test: add unit tests for PetEntity#161

Merged
lindaeskilsson merged 6 commits into
mainfrom
test/pet-entity
Apr 8, 2026
Merged

test: add unit tests for PetEntity#161
lindaeskilsson merged 6 commits into
mainfrom
test/pet-entity

Conversation

@lindaeskilsson

@lindaeskilsson lindaeskilsson commented Apr 8, 2026

Copy link
Copy Markdown
Contributor

Closes #142

Täcker:

  • Getters och setters
  • Konstruktor med alla fält
  • onCreate() sätter createdAt och updatedAt
  • onUpdate() uppdaterar updatedAt utan att röra createdAt
  • Standardvärden är null innan persist

Summary by CodeRabbit

  • Tests
    • Added comprehensive test suite for the Pet entity covering getters/setters, full-constructor behavior (including nullable breed), default pre-persistence state, and lifecycle timestamp management (creation and update timestamps). Tests verify numeric weight handling and owner association, ensuring timestamps are set on create and updated on subsequent updates.

@coderabbitai

coderabbitai Bot commented Apr 8, 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: febdf425-8c74-47ad-8bac-0be0e6daefb0

📥 Commits

Reviewing files that changed from the base of the PR and between 1373664 and da7ff7d.

📒 Files selected for processing (1)
  • src/test/java/org/example/vet1177/entities/PetEntityTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/test/java/org/example/vet1177/entities/PetEntityTest.java

📝 Walkthrough

Walkthrough

Added a JUnit 5 test class that validates the Pet entity's getters/setters, full-constructor initialization (including nullable breed), and JPA lifecycle callbacks (@PrePersist and @PreUpdate) for createdAt/updatedAt, plus default/null pre-persistence state checks.

Changes

Cohort / File(s) Summary
Pet Entity Test Suite
src/test/java/org/example/vet1177/entities/PetEntityTest.java
New JUnit 5 test class (≈175 lines). Tests: property accessors (name, species, breed, dateOfBirth, weightKg, owner), full-constructor field population, breed nullable behavior, lifecycle callbacks setting/updating createdAt and updatedAt, and default/null state before persistence.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • Feature/pet entity #17: Adds/defines Pet entity behavior (constructor, accessors, JPA lifecycle callbacks) which these tests exercise.
  • Feat/pet controller pet dto #91: Related changes to Pet entity fields/validation (e.g., dateOfBirth) that this test may validate against.

Suggested labels

test

Suggested reviewers

  • annikaholmqvist94
  • johanbriger
  • TatjanaTrajkovic

Poem

🐰
I hop through tests with careful paw,
Checking fields and lifecycle law.
Names and dates, weights that fit —
Timestamps set, the logs commit.
A gentle rabbit says: "All green, hop on!" 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR partially addresses linked issue #142. It covers constructor testing and lifecycle callbacks (@PrePersist/@PreUpdate), but lacks validation tests for @NotBlank, @NotNull, and @Positive constraints. Add validation tests for @NotBlank on name/species, @NotNull on dateOfBirth, @Positive on weightKg, and confirm breed nullability as specified in issue #142.
Docstring Coverage ⚠️ Warning Docstring coverage is 22.73% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding unit tests for PetEntity, which aligns with the changeset.
Out of Scope Changes check ✅ Passed All changes are scoped to testing PetEntity as specified in linked issue #142; no out-of-scope modifications detected.

✏️ 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/pet-entity

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 (3)
src/test/java/org/example/vet1177/entities/PetEntityTest.java (3)

10-10: Consider using the standard AssertJ import.

Assertions is the conventional entry point for AssertJ, providing both object and collection assertions.

Suggested change
-import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
🤖 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/PetEntityTest.java` at line 10,
Replace the nonstandard static import AssertionsForClassTypes.assertThat used in
PetEntityTest with the conventional AssertJ entry point by importing
Assertions.assertThat (use a static import of
org.assertj.core.api.Assertions.assertThat or import
org.assertj.core.api.Assertions and call Assertions.assertThat) so the test uses
the standard AssertJ API; update the import statement referencing assertThat
accordingly in PetEntityTest.java.

109-116: Strengthen this test to verify updatedAt actually changes.

After onCreate(), updatedAt is already non-null, so assertThat(pet.getUpdatedAt()).isNotNull() always passes trivially. Consider verifying that updatedAt is refreshed to a new value.

Suggested improvement
 `@Test`
 void onUpdate_shouldRefreshUpdatedAt() {
     pet.onCreate();
+    Instant originalUpdatedAt = pet.getUpdatedAt();

     pet.onUpdate();

-    assertThat(pet.getUpdatedAt()).isNotNull();
+    assertThat(pet.getUpdatedAt()).isNotNull();
+    assertThat(pet.getUpdatedAt()).isAfterOrEqualTo(originalUpdatedAt);
 }
🤖 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/PetEntityTest.java` around lines
109 - 116, The test in PetEntityTest currently only checks non-null updatedAt
after calling pet.onUpdate(), which always passes because pet.onCreate() already
sets it; update the test to capture the timestamp after pet.onCreate() (e.g.,
Instant old = pet.getUpdatedAt()), then call pet.onUpdate(), and assert that
pet.getUpdatedAt() is not equal to old and is after/greater than old (you can
introduce a tiny delay or use time assertions) to ensure onUpdate() actually
refreshes the timestamp; reference methods: onCreate(), onUpdate(), and
getUpdatedAt() on the pet instance.

12-175: Missing validation constraint tests from linked issue #142.

The linked issue requires testing Bean Validation annotations, but these are not covered:

  • @NotBlank on name and species (reject null/blank)
  • @NotNull on dateOfBirth
  • @Positive on weightKg

Consider adding tests using a Validator instance to verify constraints:

import jakarta.validation.Validation;
import jakarta.validation.Validator;

`@Test`
void name_shouldRejectBlankValue() {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    pet.setName("");
    pet.setSpecies("hund");
    pet.setDateOfBirth(LocalDate.now());
    pet.setWeightKg(new BigDecimal("5.0"));
    
    var violations = validator.validate(pet);
    assertThat(violations).anyMatch(v -> v.getPropertyPath().toString().equals("name"));
}

Do you want me to generate the complete validation test suite, or open an issue to track this?

🤖 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/PetEntityTest.java` around lines
12 - 175, Add Bean Validation tests to PetEntityTest that use a Validator
(Validation.buildDefaultValidatorFactory().getValidator()) to assert constraint
violations for Pet fields: create tests named name_shouldRejectBlankValue and
species_shouldRejectBlankValue that set pet.setName("") / pet.setSpecies("")
respectively while populating other required fields (dateOfBirth, weightKg,
species/name) with valid values and assert violations contain propertyPath
"name" or "species"; add dateOfBirth_shouldRejectNull that leaves dateOfBirth
null and asserts a violation for "dateOfBirth"; and add
weightKg_shouldRejectNonPositive that sets weightKg to zero or negative and
asserts a violation for "weightKg". Ensure each test uses the same Validator
instance and checks violations.stream().anyMatch(v ->
v.getPropertyPath().toString().equals("<fieldName>")).
🤖 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/entities/PetEntityTest.java`:
- Around line 29-58: In PetEntityTest, fix the typos in the test method names so
test reports/readability are correct: rename
setSpeices_shouldStoreAndReturnCorrectValue to
setSpecies_shouldStoreAndReturnCorrectValue,
setBread_shouldStoreAndReturnCorrectValue to
setBreed_shouldStoreAndReturnCorrectValue,
setDateOfBirth_shouldStorAndReturnCorrectValue to
setDateOfBirth_shouldStoreAndReturnCorrectValue, and
setWeigthKg_shouldStoreAndReturnCorrectValue to
setWeightKg_shouldStoreAndReturnCorrectValue; update only the method names in
the PetEntityTest class so the tests and assertions (pet.setSpecies,
pet.setBreed, pet.setDateOfBirth, pet.setWeightKg) remain unchanged.

---

Nitpick comments:
In `@src/test/java/org/example/vet1177/entities/PetEntityTest.java`:
- Line 10: Replace the nonstandard static import
AssertionsForClassTypes.assertThat used in PetEntityTest with the conventional
AssertJ entry point by importing Assertions.assertThat (use a static import of
org.assertj.core.api.Assertions.assertThat or import
org.assertj.core.api.Assertions and call Assertions.assertThat) so the test uses
the standard AssertJ API; update the import statement referencing assertThat
accordingly in PetEntityTest.java.
- Around line 109-116: The test in PetEntityTest currently only checks non-null
updatedAt after calling pet.onUpdate(), which always passes because
pet.onCreate() already sets it; update the test to capture the timestamp after
pet.onCreate() (e.g., Instant old = pet.getUpdatedAt()), then call
pet.onUpdate(), and assert that pet.getUpdatedAt() is not equal to old and is
after/greater than old (you can introduce a tiny delay or use time assertions)
to ensure onUpdate() actually refreshes the timestamp; reference methods:
onCreate(), onUpdate(), and getUpdatedAt() on the pet instance.
- Around line 12-175: Add Bean Validation tests to PetEntityTest that use a
Validator (Validation.buildDefaultValidatorFactory().getValidator()) to assert
constraint violations for Pet fields: create tests named
name_shouldRejectBlankValue and species_shouldRejectBlankValue that set
pet.setName("") / pet.setSpecies("") respectively while populating other
required fields (dateOfBirth, weightKg, species/name) with valid values and
assert violations contain propertyPath "name" or "species"; add
dateOfBirth_shouldRejectNull that leaves dateOfBirth null and asserts a
violation for "dateOfBirth"; and add weightKg_shouldRejectNonPositive that sets
weightKg to zero or negative and asserts a violation for "weightKg". Ensure each
test uses the same Validator instance and checks violations.stream().anyMatch(v
-> v.getPropertyPath().toString().equals("<fieldName>")).
🪄 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: 6434f252-6326-4361-8716-08f7fb76fa22

📥 Commits

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

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

Comment thread src/test/java/org/example/vet1177/entities/PetEntityTest.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!

@lindaeskilsson
lindaeskilsson merged commit 050710a into main Apr 8, 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: PetEntityTest – validering och lifecycle callbacks

2 participants