Skip to content

Unit Tests for BookingService.java, Overloaded Constructor in Booking…#7

Merged
Xeutos merged 2 commits intomainfrom
feature/tests
Jan 14, 2026
Merged

Unit Tests for BookingService.java, Overloaded Constructor in Booking…#7
Xeutos merged 2 commits intomainfrom
feature/tests

Conversation

@Xeutos
Copy link
Copy Markdown

@Xeutos Xeutos commented Jan 13, 2026

…Service.java to work in testing environment.

Removed unnecessary params for BookingService.java that were not utilized in current implementation.

Summary by CodeRabbit

  • Refactor

    • Simplified startup and service initialization for bookings.
    • Reduced internal dependencies to make booking logic easier to configure.
  • Bug Fix / Validation

    • Improved guest-capacity validation to prevent overbooking.
    • Clarified error messaging for invalid price/booking scenarios.
  • Tests

    • Added unit tests covering booking price calculations and edge cases.

✏️ Tip: You can customize this high-level summary in your review settings.

…Service.java to work in testing environment.

Removed unnecessary params for BookingService.java that were not utilized in current implementation.

Co-authored-by: Andreas Kaiberger <andreas.kaiberger@gmail.com>
Co-authored-by: Martin Karlsson <Martin.Karlsson@iths.se>
Co-authored-by: Rickard Ankar <rickard.ankar@iths.se>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jan 13, 2026

📝 Walkthrough

Walkthrough

Refactors BookingService to remove EntityManagerFactory, add a test-mode constructor using a price BigDecimal, and make guest-limit validation conditional on test mode. Updates App.main signature from main(String[] args) to main() and adjusts BookingService instantiation. Adds unit tests for price calculation and validations.

Changes

Cohort / File(s) Summary
App entry point & wiring
src/main/java/org/example/App.java
Changed static void main(String[] args)static void main(); updated BookingService instantiation to new BookingService(bookingRepository) (removed EntityManagerFactory parameter).
BookingService refactor
src/main/java/org/example/BookingService.java
Removed EntityManagerFactory field and constructor; added BookingService(BookingRepository) and BookingService(BigDecimal priceClass) (testMode); conditionalized validateValues() to skip repository guest-limit checks in test mode; adjusted error message in calculateTotalPrice().
Tests added
src/test/java/org/example/BookingServiceTest.java
New JUnit 5 tests for calculateTotalPrice() covering normal calculation, zero-price exception, and several invalid input scenarios.

Sequence Diagram(s)

(skip — changes are refactor/configuration and small control-flow tweaks that do not introduce a new multi-component sequential feature)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 A rabbit hops through code so bright,
Constructors trimmed to just what's right,
Tests spring up to guard the fee,
Guest checks pause in test-time glee,
Hooray — the booking hops with light! 🥕✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The pull request title partially covers the main changes: it mentions unit tests and an overloaded constructor for BookingService, which are present. However, it is truncated and incomplete (ending with '...'), failing to fully convey the main scope, including the removal of unnecessary parameters and changes to the main entry point. Complete the title to fully describe the changes, such as: 'Add unit tests and refactor BookingService constructor for testing' to provide clarity on all main modifications.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing touches
  • 📝 Generate docstrings


📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d52b50 and 7560218.

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

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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

@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

🤖 Fix all issues with AI agents
In @src/test/java/org/example/BookingServiceTest.java:
- Around line 47-57: The test method name
calculateTotalPriceShouldReturnNegativeValueIfStartDateIsBeforeEndDate is
misleading because the test sets start after end; rename the method in
BookingServiceTest to
calculateTotalPriceShouldReturnNegativeValueIfStartDateIsAfterEndDate (or
calculateTotalPriceShouldReturnNegativeValueIfEndDateIsBeforeStartDate) and
update any references/usages accordingly to match the new name while keeping the
test body and assertion against bookingService.calculateTotalPrice unchanged.
🧹 Nitpick comments (2)
src/main/java/org/example/BookingService.java (2)

9-21: Consider using dependency injection instead of testMode flag.

Embedding test-specific logic (testMode flag) in production code is a design smell. Setting bookingRepository = null introduces latent NPE risk if the conditional logic changes.

A cleaner approach: extract an interface for guest capacity validation, inject a stub/mock in tests, or pass the max-guests value directly.

♻️ Suggested alternative approach
 public class BookingService {
     private final BookingRepository bookingRepository;
     private final BigDecimal priceClass;
-    private boolean testMode = false;
+    private final Integer maxGuestsOverride;

     public BookingService(BookingRepository bookingRepository) {
         this.bookingRepository = bookingRepository;
         priceClass = BigDecimal.valueOf(300);
+        this.maxGuestsOverride = null;
     }
-    public BookingService(BigDecimal priceClass) {
-        bookingRepository = null;
+
+    // Test constructor - provide maxGuests explicitly instead of null repository
+    public BookingService(BigDecimal priceClass, int maxGuests) {
+        this.bookingRepository = null;
         this.priceClass = priceClass;
-        testMode = true;
+        this.maxGuestsOverride = maxGuests;
     }

Then in validateValues, use maxGuestsOverride != null ? maxGuestsOverride : bookingRepository.getMaxGuests().


51-61: Inconsistent indentation.

Lines 52-60 have extra leading spaces compared to the rest of the method. Consider normalizing the indentation for readability.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e09ad6f and 5d52b50.

📒 Files selected for processing (3)
  • src/main/java/org/example/App.java
  • src/main/java/org/example/BookingService.java
  • src/test/java/org/example/BookingServiceTest.java
🔇 Additional comments (3)
src/test/java/org/example/BookingServiceTest.java (1)

12-82: Good test coverage for calculateTotalPrice validation paths.

The tests cover the main scenarios well. Consider adding a test for the max-guests validation path (non-test mode) using a mocked BookingRepository to ensure full coverage of the production code path.

src/main/java/org/example/App.java (2)

24-24: LGTM!

The simplified BookingService instantiation with only BookingRepository is cleaner and properly decouples the service from EntityManagerFactory.


9-9: Java 25 supports the main() signature; however, be aware of the trade-offs.

The project is configured for Java 25, which fully supports the simplified static void main() signature without String[] args and the public modifier (introduced in Java 21 via JEP 445). Note that this signature removes the ability to accept command-line arguments, which may be intentional if your application doesn't need them.

Comment on lines +47 to +57
@Test
void calculateTotalPriceShouldReturnNegativeValueIfStartDateIsBeforeEndDate(){
var guests = 1;
var start = LocalDate.now();
var end = LocalDate.now().minusDays(1);
var bookingService = new BookingService(BigDecimal.ONE);

var result = bookingService.calculateTotalPrice(guests, start, end);

assertThat(result).isEqualTo(BigDecimal.valueOf(-1));
}
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

Misleading test method name.

The method name calculateTotalPriceShouldReturnNegativeValueIfStartDateIsBeforeEndDate is confusing. The test actually verifies that start date is after end date (end = now minus 1 day).

Consider renaming to ...IfStartDateIsAfterEndDate or ...IfEndDateIsBeforeStartDate.

📝 Suggested fix
-    void calculateTotalPriceShouldReturnNegativeValueIfStartDateIsBeforeEndDate(){
+    void calculateTotalPriceShouldReturnNegativeValueIfStartDateIsAfterEndDate(){
📝 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
@Test
void calculateTotalPriceShouldReturnNegativeValueIfStartDateIsBeforeEndDate(){
var guests = 1;
var start = LocalDate.now();
var end = LocalDate.now().minusDays(1);
var bookingService = new BookingService(BigDecimal.ONE);
var result = bookingService.calculateTotalPrice(guests, start, end);
assertThat(result).isEqualTo(BigDecimal.valueOf(-1));
}
@Test
void calculateTotalPriceShouldReturnNegativeValueIfStartDateIsAfterEndDate(){
var guests = 1;
var start = LocalDate.now();
var end = LocalDate.now().minusDays(1);
var bookingService = new BookingService(BigDecimal.ONE);
var result = bookingService.calculateTotalPrice(guests, start, end);
assertThat(result).isEqualTo(BigDecimal.valueOf(-1));
}
🤖 Prompt for AI Agents
In @src/test/java/org/example/BookingServiceTest.java around lines 47 - 57, The
test method name
calculateTotalPriceShouldReturnNegativeValueIfStartDateIsBeforeEndDate is
misleading because the test sets start after end; rename the method in
BookingServiceTest to
calculateTotalPriceShouldReturnNegativeValueIfStartDateIsAfterEndDate (or
calculateTotalPriceShouldReturnNegativeValueIfEndDateIsBeforeStartDate) and
update any references/usages accordingly to match the new name while keeping the
test body and assertion against bookingService.calculateTotalPrice unchanged.

…StartDateIsBeforeEndDate() where logic was backwards but still functional.

Co-authored-by: Andreas Kaiberger <andreas.kaiberger@gmail.com>
Co-authored-by: Martin Karlsson <Martin.Karlsson@iths.se>
Co-authored-by: Rickard Ankar <rickard.ankar@iths.se>
@Xeutos Xeutos merged commit 62969a6 into main Jan 14, 2026
2 checks passed
@Xeutos Xeutos deleted the feature/tests branch January 14, 2026 08:58
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