Repair a Rewards Calculator: Three Red Tests in a Java Service
StringsModel answerLast 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:
calculatesTriplePointsForRestaurantsreturnsUnknownWhenMerchantCodeMissingaggregatesDailyPointsCorrectly
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
- Describe how you would reproduce the failures and how you would read each assertion message and stack trace to locate the cause.
- Explain how you isolate each defect before changing code.
- 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).
- Restaurant spending is not earning triple points, because of how the category string is checked against
- Explain how you confirm there are no regressions.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This task rewards debugging discipline more than algorithmic cleverness. The loop I follow is: reproduce, classify, isolate, fix minimally, verify. I state my assumptions about the code up front because the project is not shown.
1. Reproduce and classify
- Run the full suite (
mvn testor./gradlew test) and record which tests pass. That is the regression baseline. - Run each failing test alone, for example
mvn -Dtest=RewardsCalculatorTest#calculatesTriplePointsForRestaurants test, so output is not mixed. - Classify each failure:
AssertionError: expected X but was Yis a logic bug. Compare the numbers or values and ask what rule would produce Y.- An exception such as
NullPointerExceptionis a crash bug. Read the trace from the top to the first frame in project code, not JUnit or reflection frames.
2. Isolate before editing
Read the test's arrange, act and assert sections, trace the inputs into production code, and form one hypothesis per failure. Confirm it with a breakpoint or a temporary log line. Fix production code only. A test should be changed only if it is provably wrong, and I would say so explicitly.
3. The three likely defects and fixes
Restaurant multiplier. The symptom is a points total one third of what was expected. The likely cause is a check like txn.getCategory() == "RESTAURANT". This is wrong twice over: == compares references, not contents, and the casing does not match the test data "Restaurant". Fix by comparing by value, tolerating case and whitespace, and putting the constant first so a null category cannot throw.
private int multiplierFor(String category) {
if (category != null && "Restaurant".equalsIgnoreCase(category.trim())) {
return 3;
}
return 1;
}
Missing merchant code. The symptom is an NPE inside the resolver. The cause is dereferencing the code (trim(), toUpperCase()) or using it as a key in an immutable map, which rejects null keys. The test name defines the contract: missing means "UNKNOWN". I treat null, empty and whitespace-only as missing.
public String resolve(String merchantCode) {
if (merchantCode == null || merchantCode.isBlank()) {
return UNKNOWN;
}
return merchantsByCode.getOrDefault(
merchantCode.trim().toUpperCase(Locale.ROOT), UNKNOWN);
}
The guard comes before any dereference. Valid codes behave as before.
Daily aggregation off-by-one. The symptom is a missing last day or a final total of 0. The usual causes are start.datesUntil(end), which excludes end, or a loop bounded by days - 1. The test treats the range as inclusive on both ends. Fix by extending the upper bound, and bucket by LocalDate rather than a timestamp so late-evening transactions are not shifted to another day.
public Map<LocalDate, Long> aggregate(List<Transaction> txns, LocalDate start, LocalDate end) {
if (end.isBefore(start)) {
throw new IllegalArgumentException("end must not be before start");
}
Map<LocalDate, Long> totals = new LinkedHashMap<>();
start.datesUntil(end.plusDays(1)).forEach(d -> totals.put(d, 0L));
for (Transaction t : txns) {
LocalDate day = t.getDate();
if (totals.containsKey(day)) {
totals.merge(day, calculator.calculatePoints(t), Long::sum);
}
}
return totals;
}
Pre-seeding every day with 0 makes days without spending appear explicitly, and transactions outside the range are ignored. If the existing tests expect a different behavior for an inverted range, I would match them rather than throw.
4. Verify
- Rerun each of the three tests individually, then the whole suite and compare with the baseline. Nothing that passed before may fail now.
- Review the diff. Each file should contain exactly one behavioral change, which makes review easy and keeps the blast radius small.
- Think through neighbors of each fix: categories like
"restaurants"or"Fast Food"should still earn 1x unless the spec says otherwise; an unknown but non-null merchant code should return"UNKNOWN"; a single-day range should return exactly one entry.
5. Preventing recurrence
- Edge-case tests (written in a follow-up change, since this task forbids adding them now): null, empty and mixed-case inputs; single-day, multi-day and inverted ranges; transactions at 23:59 and 00:00 on range boundaries.
- Input validation at the boundary: normalize categories and merchant codes once on ingestion, or use an enum for categories so string comparison disappears.
- Static analysis: enable rules that flag string comparison with
==and unguarded dereferences (SpotBugs, Error Prone, nullness annotations). - Review checklist: Are ranges inclusive or exclusive and is that documented? What happens on null or empty? Are strings compared by value? Are dates bucketed in a consistent time zone?
- CI: run the full suite on every pull request so a regression is caught before merge.
Common mistakes
- Editing the test to match the buggy output.
- Fixing symptoms (for example, catching the NPE and returning a default) rather than the missing guard.
- Using
toUpperCase()without a locale, which can misbehave in some locales. - Changing the range semantics for all callers without checking other tests.
- Skipping the full-suite rerun after the last fix.
Complexity
All three fixes are constant-time per transaction; aggregation is O(D + N) for D days in the range and N transactions.