Skip to content

test: add test cases for missing products, zero distance, duplicate I…#231

Merged
driedpampas merged 1 commit into
mainfrom
feat/routing-service-coverage
May 4, 2026
Merged

test: add test cases for missing products, zero distance, duplicate I…#231
driedpampas merged 1 commit into
mainfrom
feat/routing-service-coverage

Conversation

@driedpampas
Copy link
Copy Markdown
Member

@driedpampas driedpampas commented May 4, 2026

…Ds, and empty product lists in RoutingService

Summary by CodeRabbit

Release Notes

  • Tests
    • Strengthened test coverage for the routing service with new test cases validating the optimization algorithm's behavior across critical scenarios: successful handling of requests with missing products and warning notifications, zero-distance routes when origin and destination coordinates match, deduplication of duplicate product IDs, and proper error handling for empty product request lists.

…Ds, and empty product lists in RoutingService
@driedpampas driedpampas requested a review from a team as a code owner May 4, 2026 15:05
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 4, 2026

📝 Walkthrough

Walkthrough

Four new test cases extend coverage of RoutingService.calculateOptimalRoute for edge cases: missing product lookups with warnings, zero-distance routes, duplicate product IDs, and empty product ID requests.

Changes

Test Coverage Extension

Layer / File(s) Summary
Test Cases
src/test/java/com/p2ps/service/RoutingServiceTest.java
Four new test methods: shouldWarnWhenSomeProductsMissing verifies warnings for unmatched items; shouldHandleZeroDistanceImprovement asserts zero distance when coordinates match; shouldHandleDuplicateProductIds confirms route composition with duplicate IDs; shouldReturnEmptyResponseWhenProductIdsIsEmpty checks error status for empty requests.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • R4R35
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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 test cases for missing products, zero distance, duplicate IDs, and empty product lists to RoutingService.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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/routing-service-coverage

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

Comment @coderabbitai help to get the list of available commands and usage tips.

@driedpampas
Copy link
Copy Markdown
Member Author

@coderabbitai cancel

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 4, 2026

Tip

For best results, initiate chat on the files or code changes.

@driedpampas Sure, I'll cancel the ongoing review.

[pause]

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.

🧹 Nitpick comments (2)
src/test/java/com/p2ps/service/RoutingServiceTest.java (2)

463-477: ⚡ Quick win

Make zero-distance test deterministic about checkout handling.

assertEquals(0.0, totalDistanceMeters, ...) currently depends on implicit mock default behavior for queryForObject. Explicitly force “no checkout” in this test so route-distance intent is unambiguous.

Suggested patch
 `@Test`
 `@SuppressWarnings`("unchecked")
 void calculateOptimalRoute_shouldHandleZeroDistanceImprovement() {
     when(jdbcTemplate.queryForList(anyString(), eq(String.class), anyDouble(), anyDouble()))
             .thenReturn(List.of(STORE_ID));

     // User and product at the same location -> distance is 0
     RoutingService.ProductLocation p1 = new RoutingService.ProductLocation(ITEM_1, "P1", 47.156, 27.587, 0.9);
     when(jdbcTemplate.query(anyString(), any(RowMapper.class), any(Object[].class)))
             .thenReturn(List.of(p1));
+    when(jdbcTemplate.queryForObject(anyString(), any(RowMapper.class), anyString()))
+            .thenThrow(new org.springframework.dao.EmptyResultDataAccessException(1));

     RoutingRequest request = new RoutingRequest(47.156, 27.587, List.of(ITEM_1), 0);
     RoutingResponse response = service.calculateOptimalRoute(request);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/service/RoutingServiceTest.java` around lines 463 -
477, The test calculateOptimalRoute_shouldHandleZeroDistanceImprovement is
nondeterministic because it relies on implicit defaults for
jdbcTemplate.queryForObject (used by RoutingService.calculateOptimalRoute to
check for an existing checkout); explicitly stub that call in the test to return
the "no checkout" value your service expects (e.g., null/Optional.empty/false
depending on the queryForObject signature) so the route distance logic is
unambiguous and the assertion on response.getTotalDistanceMeters() remains
deterministic.

481-498: ⚡ Quick win

Strengthen duplicate-ID assertions to avoid false positives.

route.size() >= 2 is too permissive and can pass even if duplicate handling changes unexpectedly. Add assertions on item occurrence and warnings for the duplicated ID.

Suggested patch
         RoutingResponse response = service.calculateOptimalRoute(request);

         assertEquals("success", response.getStatus());
-        // Depending on implementation, we might have 1 product in route (unique) or 2.
-        // Current logic in getProductLocations doesn't de-duplicate, it just returns what the DB returns.
-        // If DB returns one row (because item_id is unique per store), then we have 1 product.
-        assertTrue(response.getRoute().size() >= 2); // user + at least one product
+        long item1Occurrences = response.getRoute().stream()
+                .filter(p -> ITEM_1.equals(p.getItemId()))
+                .count();
+        assertEquals(1, item1Occurrences);
+        assertTrue(response.getWarnings().stream()
+                .noneMatch(w -> w.contains(ITEM_1) && w.contains("nu a fost gasit")));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/service/RoutingServiceTest.java` around lines 481 -
498, The test calculateOptimalRoute_shouldHandleDuplicateProductIds is too
permissive; replace the generic assertTrue(response.getRoute().size() >= 2) with
precise checks: using RoutingResponse.getRoute() assert the route includes the
user/start node and at least one product node, then count occurrences of ITEM_1
in the route (e.g., stream/filter on route entries' productId) and assert the
count matches expected behavior (for current getProductLocations behavior assert
count == 1 if DB returns one row) and also assert that
RoutingResponse.getWarnings() (or similar) contains a warning about the
duplicated ID when duplicates are submitted; reference
RoutingService.ProductLocation, getProductLocations, calculateOptimalRoute,
RoutingRequest, and RoutingResponse to locate the code to update.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/test/java/com/p2ps/service/RoutingServiceTest.java`:
- Around line 463-477: The test
calculateOptimalRoute_shouldHandleZeroDistanceImprovement is nondeterministic
because it relies on implicit defaults for jdbcTemplate.queryForObject (used by
RoutingService.calculateOptimalRoute to check for an existing checkout);
explicitly stub that call in the test to return the "no checkout" value your
service expects (e.g., null/Optional.empty/false depending on the queryForObject
signature) so the route distance logic is unambiguous and the assertion on
response.getTotalDistanceMeters() remains deterministic.
- Around line 481-498: The test
calculateOptimalRoute_shouldHandleDuplicateProductIds is too permissive; replace
the generic assertTrue(response.getRoute().size() >= 2) with precise checks:
using RoutingResponse.getRoute() assert the route includes the user/start node
and at least one product node, then count occurrences of ITEM_1 in the route
(e.g., stream/filter on route entries' productId) and assert the count matches
expected behavior (for current getProductLocations behavior assert count == 1 if
DB returns one row) and also assert that RoutingResponse.getWarnings() (or
similar) contains a warning about the duplicated ID when duplicates are
submitted; reference RoutingService.ProductLocation, getProductLocations,
calculateOptimalRoute, RoutingRequest, and RoutingResponse to locate the code to
update.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 04922f74-28e0-4477-9361-d9c80d6c4fc9

📥 Commits

Reviewing files that changed from the base of the PR and between 0f1cf89 and b896fa7.

📒 Files selected for processing (1)
  • src/test/java/com/p2ps/service/RoutingServiceTest.java

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented May 4, 2026

@driedpampas driedpampas merged commit 8e5c647 into main May 4, 2026
4 checks passed
@driedpampas driedpampas deleted the feat/routing-service-coverage branch May 4, 2026 15:10
@coderabbitai coderabbitai Bot mentioned this pull request Jun 2, 2026
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.

1 participant