KatInterview

Repair a Rewards Calculator: Three Red Tests in a Java Service

StringsModel answer
MediumModel answerStringsjavadebuggingunit-testing

Last updated

Diagnose and fix three failing JUnit tests in a Java rewards service by touching at most three files, then explain how to keep similar bugs from coming back.

You are handed a small Java project for a card-rewards service. Three unit tests currently fail:

  • calculatesTriplePointsForRestaurants
  • returnsUnknownWhenMerchantCodeMissing
  • aggregatesDailyPointsCorrectly

Constraints

  • Do not add new tests, and do not weaken the existing ones.
  • Make minimal, justified changes in at most three source files.
  • Every test in the suite must pass at the end, including the ones that pass today.

What to cover

  1. Describe how you would reproduce the failures and how you would read each assertion message and stack trace to locate the cause.
  2. Explain how you isolate each defect before changing code.
  3. Implement fixes for the likely causes:
    • Restaurant spending is not earning triple points, because of how the category string is checked against "Restaurant".
    • A missing, null, or empty merchant code must resolve to "UNKNOWN" rather than crash.
    • The per-day point totals are wrong at a range boundary (an off-by-one in the daily aggregation).
  4. Explain how you confirm there are no regressions.
  5. Finally, describe how you would reduce the chance of similar bugs returning (edge-case tests, input validation, review checklist).

Since the project itself is not provided, state your assumptions about the code layout and show representative code for each fix.

Hints

Hint 1

Start by running the whole suite for a baseline, then run each failing test alone. An assertion error with expected/actual values points to a logic bug; an exception points to a crash, and the first stack frame in project code is where to look.

Hint 2

For the category and merchant bugs, think about how Java compares strings (`==` versus `equals`), casing and whitespace, and what happens when you call a method on a null reference or use a null key in an immutable map.

Hint 3

For the aggregation bug, ask whether the date range is meant to include both endpoints, and check APIs that are end-exclusive (such as `LocalDate.datesUntil`) or loops that stop one iteration early.