Skip to content

Add unit tests for Person bean#13963

Open
Perera1325 wants to merge 2 commits intowso2:masterfrom
Perera1325:add-person-unit-test
Open

Add unit tests for Person bean#13963
Perera1325 wants to merge 2 commits intowso2:masterfrom
Perera1325:add-person-unit-test

Conversation

@Perera1325
Copy link
Copy Markdown

@Perera1325 Perera1325 commented Feb 19, 2026

This pr adds basic unit tests for the Person bean located in the JAX-RS sample backend service.

The tests validate:

  • Getter and setter functionality
  • Object data consistency
  • Basic equality behavior using email field

The Person class did not have direct unit test coverage.
Adding these tests improves overall test coverage and ensures correctness of bean behavior.

<>

  • Added PersonTest.java under the test directory
  • Verified getters and setters
  • Added simple equality validation test

Type of Contribution

  • Unit Test Improvement

  • Test Coverage Enhancement

    Checklist

  • Code compiles successfully

  • No breaking changes introduced

  • Follows project structure and conventions

Summary by CodeRabbit

  • Bug Fixes
    • API now validates inputs and returns clearer errors for invalid or missing email parameters; removal now fails reliably when an entry doesn't exist.
  • Tests
    • New unit tests added to cover person creation, accessors, and equality to improve reliability.

Note: These changes may affect API error responses for invalid requests.

Copilot AI review requested due to automatic review settings February 19, 2026 10:16
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Feb 19, 2026

Walkthrough

Added input validation and error handling to PeopleService methods and introduced a new JUnit test file PersonTest.java with two tests for Person construction/getters and equality.

Changes

Cohort / File(s) Summary
Service logic updates
all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/main/java/org/wso2/am/integration/services/jaxrs/peoplesample/PeopleService.java
Added input validation for email in addPerson, addPerson(email, firstName, lastName), getByEmail, checkPersonByEmail, and removePerson; return/throw behavior adjusted for invalid/missing entries; minor reordering in getPeople() initialization.
New Test Suite
all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/test/java/org/wso2/am/integration/services/jaxrs/peoplesample/bean/PersonTest.java
Added PersonTest with testPersonConstructorAndGetters() and testPersonEquality() using JUnit assertions validating Person field setters/getters and equality via email.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 I hopped through methods, tidy and bright,
I checked each email, kept logic tight,
Two tests now bound the Person's trail,
Validation strong — I left my tail! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add unit tests for Person bean' accurately reflects the main change—adding PersonTest.java with unit tests for the Person class, which is the primary focus of the PR.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/test/java/org/wso2/am/integration/services/jaxrs/peoplesample/bean/PersonTest.java`:
- Around line 22-32: The test testPersonEquality currently compares only the
email strings and uses two computed values in the wrong argument order, so
update it to assert object equality: create two Person instances with identical
fields and use Assert.assertEquals(expectedPerson, actualPerson) (or
Assert.assertTrue(p1.equals(p2))) to verify Person.equals()/hashCode() behavior,
or if you only intend to test the email accessor keep the method name and use
Assert.assertEquals("[email protected]", p1.getEmail()) with the expected-first
argument order; reference Person, testPersonEquality, equals(), and
Assert.assertEquals when making the change.

Comment on lines +22 to +32
@Test
public void testPersonEquality() {

Person p1 = new Person();
p1.setEmail("[email protected]");

Person p2 = new Person();
p2.setEmail("[email protected]");

Assert.assertEquals(p1.getEmail(), p2.getEmail());
}
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.

⚠️ Potential issue | 🟡 Minor

testPersonEquality does not test object equality and can never fail.

Two concrete issues:

  1. Trivially-true assertion: Assert.assertEquals(p1.getEmail(), p2.getEmail()) only compares two identical String literals — it will always pass regardless of whether Person implements equals()/hashCode() correctly. This gives false confidence.

  2. Wrong assertEquals argument order: JUnit convention is (expected, actual). Both arguments here are computed values, so a failure message would be unhelpful.

To meaningfully test equality, assert on the Person objects directly (if equals() is implemented) or at minimum fix the argument order and rename the method to reflect what is actually being tested:

🐛 Proposed fix
-    `@Test`
-    public void testPersonEquality() {
-
-        Person p1 = new Person();
-        p1.setEmail("[email protected]");
-
-        Person p2 = new Person();
-        p2.setEmail("[email protected]");
-
-        Assert.assertEquals(p1.getEmail(), p2.getEmail());
-    }
+    `@Test`
+    public void testPersonEqualityBySameEmail() {
+        Person p1 = new Person();
+        p1.setEmail("[email protected]");
+
+        Person p2 = new Person();
+        p2.setEmail("[email protected]");
+
+        // Comparing email field values (expected, actual)
+        Assert.assertEquals("[email protected]", p1.getEmail());
+        Assert.assertEquals("[email protected]", p2.getEmail());
+    }
+
+    `@Test`
+    public void testPersonEqualityByObject() {
+        // Uncomment if Person overrides equals()/hashCode()
+        // Person p1 = new Person();
+        // p1.setEmail("[email protected]");
+        // Person p2 = new Person();
+        // p2.setEmail("[email protected]");
+        // Assert.assertEquals(p1, p2);
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/test/java/org/wso2/am/integration/services/jaxrs/peoplesample/bean/PersonTest.java`
around lines 22 - 32, The test testPersonEquality currently compares only the
email strings and uses two computed values in the wrong argument order, so
update it to assert object equality: create two Person instances with identical
fields and use Assert.assertEquals(expectedPerson, actualPerson) (or
Assert.assertTrue(p1.equals(p2))) to verify Person.equals()/hashCode() behavior,
or if you only intend to test the email accessor keep the method name and use
Assert.assertEquals("[email protected]", p1.getEmail()) with the expected-first
argument order; reference Person, testPersonEquality, equals(), and
Assert.assertEquals when making the change.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds unit tests for the Person bean class in the JAX-RS sample backend service to improve test coverage. The tests validate basic bean functionality including getters, setters, and field equality.

Changes:

  • Added PersonTest.java with two test methods covering getter/setter functionality and email field equality validation

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +23 to +31
public void testPersonEquality() {

Person p1 = new Person();
p1.setEmail("[email protected]");

Person p2 = new Person();
p2.setEmail("[email protected]");

Assert.assertEquals(p1.getEmail(), p2.getEmail());
Copy link

Copilot AI Feb 19, 2026

Choose a reason for hiding this comment

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

The test name testPersonEquality is misleading because it only compares email fields rather than testing object equality (using equals() method). Consider renaming to testPersonEmailEquality or testGetEmailReturnsCorrectValue to accurately reflect what is being tested.

Copilot uses AI. Check for mistakes.
@CLAassistant
Copy link
Copy Markdown

CLAassistant commented Feb 19, 2026

CLA assistant check
All committers have signed the CLA.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/main/java/org/wso2/am/integration/services/jaxrs/peoplesample/PeopleService.java`:
- Around line 46-58: Remove the call to setInitPeople() from getPeople and
instead run setInitPeople once at bean initialization by annotating the
setInitPeople method with `@PostConstruct`; this ensures the backing map persons
is populated once (so getByEmail / checkPersonByEmail can find entries) and
avoids re-initializing on every getPeople call while leaving getPeople to only
build/return the requested page of Person objects.
- Line 41: In PeopleService update the last-name template string used when
setting newPerson.lastName: replace the misspelled "testLasrName%d" with the
correct "testLastName%d" in the call
newPerson.setLastName(String.format("testLasrName%d", count)) so stored entries
in the persons map use the correct lastName value.
- Around line 50-53: The PeopleService endpoint currently uses page and pageSize
directly in the loop (in the for loop that constructs Person using
String.format("person+%[email protected]", (pageSize * (page - 1) + index + 1))) which
allows page=0 or pageSize<=0 to produce malformed emails; add input validation
at the start of the request handler (or the method that computes the list) to
ensure both page and pageSize are >= 1 (or return an HTTP
400/IllegalArgumentException for invalid values) and normalize or clamp values
as appropriate before running the loop so the computed index expression cannot
become negative. Ensure the validation references the page and pageSize
parameters in PeopleService and short-circuits before the person list creation.
- Around line 60-67: The addPerson(String email) method currently validates and
returns a new Person but does not persist it; update addPerson(String email) to
mirror the three-argument overload by inserting into the backing map using
persons.putIfAbsent(email, person) (or equivalent) and return the resident value
(the existing person if present, otherwise the newly created person) so that
getByEmail, checkPersonByEmail, and removePerson will observe the new entry.

Person newPerson = new Person();
newPerson.setEmail(String.format("test-%[email protected]", count));
newPerson.setFirstName(String.format("testUser%d", count));
newPerson.setLastName(String.format("testLasrName%d", count));
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.

⚠️ Potential issue | 🟡 Minor

Typo: "testLasrName%d""testLastName%d"

The misspelled last-name template will be stored in the persons map and could cause test assertions on lastName fields to fail unexpectedly.

🐛 Proposed fix
-            newPerson.setLastName(String.format("testLasrName%d", count));
+            newPerson.setLastName(String.format("testLastName%d", count));
📝 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
newPerson.setLastName(String.format("testLasrName%d", count));
newPerson.setLastName(String.format("testLastName%d", count));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/main/java/org/wso2/am/integration/services/jaxrs/peoplesample/PeopleService.java`
at line 41, In PeopleService update the last-name template string used when
setting newPerson.lastName: replace the misspelled "testLasrName%d" with the
correct "testLastName%d" in the call
newPerson.setLastName(String.format("testLasrName%d", count)) so stored entries
in the persons map use the correct lastName value.

Comment on lines +46 to 58
public Collection<Person> getPeople(int page, int pageSize) {

Collection<Person> person = new ArrayList<>(pageSize);

for (int index = 0; index < pageSize; ++index) {
person.add(new Person(
String.format("person+%[email protected]",
(pageSize * (page - 1) + index + 1))));
}

setInitPeople();
return person;
}
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.

⚠️ Potential issue | 🟠 Major

setInitPeople() is a disconnected side effect and should be called at bean initialization, not inside getPeople

The person list returned by getPeople contains "[email protected]" entries built inline; the setInitPeople() call on line 56 populates persons (the backing map) with entirely different "[email protected]" entries. These two data sets are never reconciled, so:

  1. The objects returned to callers are never stored in persons, making them unreachable via getByEmail / checkPersonByEmail.
  2. setInitPeople() runs on every getPeople invocation — wasteful, even if putIfAbsent keeps it idempotent.

The idiomatic Spring pattern is to annotate setInitPeople() with @PostConstruct so the backing store is populated exactly once after dependency injection completes, rather than as a side effect of a request-scoped method.

♻️ Proposed fix — move initialization to `@PostConstruct`
+import javax.annotation.PostConstruct;
 ...
+    `@PostConstruct`
     public void setInitPeople() {
         for (int count = 1; count <= 10; count++) {
             ...
         }
     }

     public Collection<Person> getPeople(int page, int pageSize) {
         Collection<Person> person = new ArrayList<>(pageSize);
         for (int index = 0; index < pageSize; ++index) {
             person.add(new Person(
                     String.format("person+%[email protected]",
                             (pageSize * (page - 1) + index + 1))));
         }
-        setInitPeople();
         return person;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/main/java/org/wso2/am/integration/services/jaxrs/peoplesample/PeopleService.java`
around lines 46 - 58, Remove the call to setInitPeople() from getPeople and
instead run setInitPeople once at bean initialization by annotating the
setInitPeople method with `@PostConstruct`; this ensures the backing map persons
is populated once (so getByEmail / checkPersonByEmail can find entries) and
avoids re-initializing on every getPeople call while leaving getPeople to only
build/return the requested page of Person objects.

Comment on lines +50 to +53
for (int index = 0; index < pageSize; ++index) {
person.add(new Person(
String.format("person+%[email protected]",
(pageSize * (page - 1) + index + 1))));
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.

⚠️ Potential issue | 🟠 Major

Missing validation for page and pageSize can produce malformed email addresses

With page = 0 the expression pageSize * (page - 1) + index + 1 evaluates to a negative number, producing strings like "[email protected]". Callers of this integration-test endpoint can easily pass page = 0 by accident.

🛡️ Proposed guard
     public Collection<Person> getPeople(int page, int pageSize) {
+        if (page < 1) {
+            throw new IllegalArgumentException("page must be >= 1");
+        }
+        if (pageSize < 0) {
+            throw new IllegalArgumentException("pageSize must be >= 0");
+        }
         Collection<Person> person = new ArrayList<>(pageSize);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/main/java/org/wso2/am/integration/services/jaxrs/peoplesample/PeopleService.java`
around lines 50 - 53, The PeopleService endpoint currently uses page and
pageSize directly in the loop (in the for loop that constructs Person using
String.format("person+%[email protected]", (pageSize * (page - 1) + index + 1))) which
allows page=0 or pageSize<=0 to produce malformed emails; add input validation
at the start of the request handler (or the method that computes the list) to
ensure both page and pageSize are >= 1 (or return an HTTP
400/IllegalArgumentException for invalid values) and normalize or clamp values
as appropriate before running the loop so the computed index expression cannot
become negative. Ensure the validation references the page and pageSize
parameters in PeopleService and short-circuits before the person list creation.

Comment on lines +60 to 67
public Person addPerson(String email) {

return new Person( email );
if (email == null || email.isEmpty()) {
throw new IllegalArgumentException("Email cannot be null or empty");
}

return new Person(email);
}
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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

find . -type f -name "PeopleService.java" | head -5

Repository: wso2/product-apim

Length of output: 222


🏁 Script executed:

cat -n ./all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/main/java/org/wso2/am/integration/services/jaxrs/peoplesample/PeopleService.java

Repository: wso2/product-apim

Length of output: 4764


🏁 Script executed:

#!/bin/bash
# Find REST resource files that might call these addPerson methods
find . -type f -name "*Resource.java" -o -name "*Controller.java" | grep -i people

Repository: wso2/product-apim

Length of output: 43


🏁 Script executed:

#!/bin/bash
# Find all Java files that reference PeopleService
rg -l "PeopleService" --type=java

Repository: wso2/product-apim

Length of output: 694


🏁 Script executed:

cat -n ./all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/main/java/org/wso2/am/integration/services/jaxrs/peoplesample/PeopleRestService.java

Repository: wso2/product-apim

Length of output: 6224


🏁 Script executed:

#!/bin/bash
# Search for all calls to addPerson to confirm usage patterns
rg -n "addPerson\s*\(" --type=java -A2 -B2

Repository: wso2/product-apim

Length of output: 6320


addPerson(String email) validates the input but never persists the new Person to the backing store

The single-argument addPerson creates and returns a Person without calling persons.putIfAbsent. This is inconsistent with the three-argument overload (lines 94–111) which does store the person. The REST endpoint at line 47–48 of PeopleRestService.java exposes this method via a @PUT /people operation, meaning any HTTP PUT request returns a person that is immediately invisible to getByEmail, checkPersonByEmail, and removePerson.

🐛 Proposed fix — persist the person (mirroring the 3-arg overload)
     public Person addPerson(String email) {
         if (email == null || email.isEmpty()) {
             throw new IllegalArgumentException("Email cannot be null or empty");
         }
-        return new Person(email);
+        final Person person = new Person(email);
+        if (persons.putIfAbsent(email, person) != null) {
+            throw new PersonAlreadyExistsException(email);
+        }
+        return person;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@all-in-one-apim/modules/integration/tests-common/backend-service/jaxrs-app/src/main/java/org/wso2/am/integration/services/jaxrs/peoplesample/PeopleService.java`
around lines 60 - 67, The addPerson(String email) method currently validates and
returns a new Person but does not persist it; update addPerson(String email) to
mirror the three-argument overload by inserting into the backing map using
persons.putIfAbsent(email, person) (or equivalent) and return the resident value
(the existing person if present, otherwise the newly created person) so that
getByEmail, checkPersonByEmail, and removePerson will observe the new entry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants