Isolate and Repair Failing Java Unit Tests
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Prompt
You inherit a compact Java codebase that computes loyalty points on card transactions, where three existing JUnit tests are currently red:
calculatesTriplePointsForRestaurantsreturnsUnknownWhenMerchantCodeMissingaggregatesDailyPointsCorrectly
Without adding, deleting, or altering any unit tests, repair the production logic using minimal, targeted edits across at most three source files until the entire suite turns green. Describe how you diagnose the failures step by step—capturing a clean baseline run, interpreting assertion mismatches alongside exception stack traces, isolating each defect in dependency order, and confirming zero regressions across previously passing tests.
Next, show concrete Java repairs for the three underlying bugs: fixing string comparison on the 'Restaurant' category, returning "UNKNOWN" safely whenever merchantCode is null or blank, and correcting an off-by-one boundary defect in daily point summation. Conclude by outlining engineering safeguards that keep similar defects from slipping back into production.
Scope & Expectations
- Establish a reproducible baseline run and explain how assertion failures differ diagnostically from uncaught runtime exceptions.
- Isolate and repair defects from leaf helpers upward, touching no more than three production Java files and leaving every existing test untouched.
- Address Java reference-equality pitfalls on
'Restaurant', null/whitespace handling onmerchantCode, and collection or date-window off-by-one boundaries. - Propose layered follow-up defenses spanning boundary test coverage, stronger domain types and input normalization, static analysis in CI, and code-review checks.
Step-by-step walkthrough
Reproduce the failures and record a clean baseline
Note: the prompt names the three failing unit tests without providing the Java source files. Below we walk through a concrete, minimal three-file rewards project built around those exact test names; the same debugging workflow applies to any Java codebase you are handed.
Before touching a single line of production code, run the entire test suite from a clean build and write down the exact starting state. In software engineering, a baseline is this initial snapshot of passing and failing tests, and a regression is when a test that used to pass starts failing after your change.
- Run a clean build and full test suite so no stale
.classfiles hide or fake a result:
Maven: mvn clean test Gradle: ./gradlew clean test- Record the exact counts — for example:
47 tests run, 44 passed, 2 failed, 1 error. At the end of your work, all 47 must pass without editing or disabling any test. - Run each failing test in isolation so you get fast feedback in under a second while investigating:
mvn -Dtest=RewardsCalculatorTest#calculatesTriplePointsForRestaurants test ./gradlew test --tests "*RewardsCalculatorTest.calculatesTriplePointsForRestaurants"- Run the failing tests twice in a row. If a test fails every single time with the exact same numbers, you are hunting a deterministic logic bug rather than a random timing or ordering issue.
Suppose your baseline test report prints:
Failures: RewardsCalculatorTest.calculatesTriplePointsForRestaurants:31 expected: <300> but was: <100> DailyPointsAggregatorTest.aggregatesDailyPointsCorrectly:44 expected: <75> but was: <30> Errors: MerchantResolverTest.returnsUnknownWhenMerchantCodeMissing:18 java.lang.NullPointerException: Cannot invoke "String.trim()" because "merchantCode" is null at com.example.rewards.MerchantResolver.categoryFor(MerchantResolver.java:22) at com.example.rewards.MerchantResolverTest.returnsUnknownWhenMerchantCodeMissing(MerchantResolverTest.java:18)- Run a clean build and full test suite so no stale
Separate crashes from wrong answers and pick the fix order
JUnit separates broken tests into two buckets, and each bucket tells you how to read it:
- Assertion failure (
expected: <X> but was: <Y>): The method finished without crashing, but returned the wrong value. Compareexpectedandactualnumerically — their ratio (300vs100is3xvs1x) or difference often points straight to the skippedifbranch or loop item. - Error (an uncaught exception): The code crashed before reaching the assertion. Read the stack trace — the list of active method calls at the moment of the crash — and jump to the top-most line inside your own production package (
MerchantResolver.java:22), skipping JUnit or reflection lines below it.
Before guessing why
aggregatesDailyPointsCorrectlygot30instead of75, check how the three classes call one another:DailyPointsAggregator.pointsOn(...) | v calls pointsFor(txn) on each matching day's transaction RewardsCalculator.pointsFor(...) | v may look up category from merchant code MerchantResolver.categoryFor(...)Always fix from the bottom of the call graph upward. Because
DailyPointsAggregatorcallsRewardsCalculator, a restaurant-points bug insideRewardsCalculatoralso corrupts the daily total! FixingMerchantResolverandRewardsCalculatorfirst strips away downstream noise soDailyPointsAggregatorshows only its own bug.- Assertion failure (
Fix 1: Compare String contents with equals, not ==
Open
RewardsCalculatorTest.calculatesTriplePointsForRestaurants(line 31) first to read the specification. Suppose it parses a$100.00(10000cents) restaurant transaction from a CSV line and expects300points (3points per dollar), but gets100(1point per dollar). Now inspectRewardsCalculator.java:// RewardsCalculator.java (before) public long pointsFor(Transaction txn) { long dollars = txn.amountCents() / 100; if (txn.category() == "Restaurant") { // BUG: compares object references, not text! return dollars * 3; } return dollars; }In Java,
==on objects asks "do both sides point to the exact same object in memory?", not "do both strings contain the same characters?". Why did other tests pass? Java uses string interning, meaning hardcoded string literals like"Restaurant"share one pooled object in memory. A test that buildsnew Transaction(..., "Restaurant", ...)passes by accident, whereasTransaction.parse("2024-03-01,m-42,Restaurant,10000")slices out a brand-newStringobject on the heap:String literal in code: "Restaurant" -----> [ Heap object #1: "Restaurant" ] Parsed from CSV input: txn.category() ----> [ Heap object #2: "Restaurant" ] txn.category() == "Restaurant" -> false (object #2 != object #1) "Restaurant".equals(txn.category()) -> true (same characters)Confirm your hypothesis before editing (for example, pause on a debugger breakpoint at the
ifline and checktxn.category()to verify there is no stray whitespace like" Restaurant"or casing difference like"RESTAURANT"). Then make the minimal, null-safe fix by calling.equals(...)on the constant string literal:// RewardsCalculator.java (after) public long pointsFor(Transaction txn) { long dollars = txn.amountCents() / 100; // Putting the constant first safely returns false even if txn.category() is null. if ("Restaurant".equals(txn.category())) { return dollars * 3; } return dollars; }Do not silently use
equalsIgnoreCaseunless the requirements specify case-insensitive categories — changing business rules beyond the spec can break tests that expect"restaurant"to be rejected. Re-runRewardsCalculatorTest:$100.00now yields300points and passes.Fix 2: Guard against null, empty, and blank merchant codes
Next, jump to the exact crash line from the stack trace (
MerchantResolver.java:22):// MerchantResolver.java (before) public String categoryFor(String merchantCode) { String code = merchantCode.trim().toUpperCase(); // line 22: crashes if merchantCode is null return categoriesByCode.getOrDefault(code, "UNKNOWN"); }The test name
returnsUnknownWhenMerchantCodeMissingdefines the expected behavior: when a transaction has no merchant code (null, empty"", or spaces" "), the resolver must return"UNKNOWN"instead of crashing. Add an explicit guard at the top of the method before dereferencing or looking up the code:// MerchantResolver.java (after) public String categoryFor(String merchantCode) { if (merchantCode == null) { return "UNKNOWN"; } String normalized = merchantCode.trim(); if (normalized.isEmpty()) { return "UNKNOWN"; } return categoriesByCode.getOrDefault(normalized.toUpperCase(Locale.ROOT), "UNKNOWN"); }Why write it in these three clear steps?
- Checking
merchantCode == nullfirst prevents theNullPointerException. - Trimming once into
normalizedand checkingnormalized.isEmpty()catches both""and" "on every Java version (Java 8+), and returning"UNKNOWN"early also protects immutable maps such asMap.of(...), which throwNullPointerExceptionifgetOrDefaultis ever called with anullkey. - Passing
Locale.ROOTtotoUpperCaseavoids locale-dependent bugs (for instance, on a machine set to the Turkish locale,"i".toUpperCase()produces dotted"İ"instead of"I").
Re-run
MerchantResolverTestandRewardsCalculatorTest: both pass.- Checking
Fix 3: Repair the off-by-one loop bound in DailyPointsAggregator
Now re-run
DailyPointsAggregatorTest.aggregatesDailyPointsCorrectlybefore editing the aggregator. Because Fix 1 repaired restaurant points, the failure message changes:Before Fix 1: expected: <75> but was: <30> After Fix 1: expected: <75> but was: <70>Look at the test's input list of 4 transactions for target date
2024-03-01:Index Date Category Amount Points (before Fix 1) Points (after Fix 1) 0 2024-03-01 "Grocery" $10.00 10 10 1 2024-03-01 "Restaurant" $20.00 20 (1x bug) 60 (3x fixed) 2 2024-03-02 "Travel" $50.00 (skipped: wrong date) (skipped: wrong date) 3 2024-03-01 "Gas" $5.00 (never visited!) (never visited!) ---------------------------------------------------------------------------------------- Total returned for 2024-03-01: 30 70 (want 75)The missing
5points (75 - 70 = 5) is the exact value of the last element at index3! OpenDailyPointsAggregator.java:// DailyPointsAggregator.java (before) public long pointsOn(LocalDate day, List<Transaction> txns) { long total = 0; for (int i = 0; i < txns.size() - 1; i++) { // BUG: stops at index 2 when size() is 4! Transaction txn = txns.get(i); if (txn.date().equals(day)) { total += calculator.pointsFor(txn); } } return total; }When
txns.size()is4, valid indices are0, 1, 2, 3. Writingi < txns.size() - 1(i < 3) visits only0, 1, 2— a classic off-by-one error (stopping one step too early or too late). Even better than changing< txns.size() - 1to< txns.size(), replace the manual index loop with an enhancedforloop so index arithmetic cannot go wrong at all:// DailyPointsAggregator.java (after) public long pointsOn(LocalDate day, List<Transaction> txns) { long total = 0; for (Transaction txn : txns) { if (txn.date().equals(day)) { total += calculator.pointsFor(txn); } } return total; }(Note: if your codebase aggregates by
InstantorLocalDateTimewindow rather thanLocalDate, check the boundary condition instead: usingts.isAfter(dayStart)drops transactions at exact midnight00:00:00. Always use a half-open interval[dayStart, nextDayStart)written as!ts.isBefore(dayStart) && ts.isBefore(dayStart.plusDays(1)).)Verify zero regressions and review the diff
Once all three targeted tests pass individually, verify the whole project systematically:
- Run a full clean build (
mvn clean testor./gradlew clean test): Confirm the summary now reads47 tests run, 47 passed, 0 failed, 0 errors— matching the baseline count with zero regressions. - Audit
git statusandgit diff: Confirm that at most three production files changed, zero test files were modified, no temporarySystem.out.printlnstatements remain, and every changed line directly fixes one verified root cause. - Check single-item and empty-list safety mentally: With
for (Transaction txn : txns), a 1-element list now processes element0(previouslyi < 0skipped it completely!), and an empty list cleanly returns0.
- Run a full clean build (
Long-term safeguards across testing, types, and CI
Because the task forbade adding tests during the bug-fix pass, propose these layered safeguards for the immediate follow-up pull request:
- Targeted edge-case unit tests: Add parameterized tests (
@ParameterizedTestwith@NullAndEmptySourceand@ValueSource(strings = {" ", "\t"})) for missing merchant codes; test category strings constructed dynamically (new String("Restaurant")) so string interning never masks==; and test daily aggregation with0items,1item, matching items at index0and indexn - 1, and exact00:00:00/23:59:59day boundaries. - Stronger domain types at the input boundary: Parse raw category strings once into a Java
enum Category { RESTAURANT, GROCERY, TRAVEL, GAS, UNKNOWN }when creating aTransaction. Comparing enums works identically with==,.equals, andswitch, eliminating string-reference and typo bugs permanently. - Boundary validation and clear null contracts: Normalize strings and reject invalid state inside the
Transactionconstructor (or mark nullable parameters explicitly with@Nullable), so downstream calculators never have to guess whether fields can benullor untrimmed. - Automated static analysis and code review checklist: Enable Error Prone or SpotBugs in CI — both fail the build automatically on
String ==reference comparisons and unguarded null dereferences — and adopt a lightweight review checklist covering:.equalson objects, null/blank input guards, collection and timestamp boundary inclusivity, explicitLocale.ROOT/ZoneId, and integer cents vs floating-point dollars.
- Targeted edge-case unit tests: Add parameterized tests (
Intuition & how it works
Think of debugging a multi-file rewards service like auditing a restaurant receipt when both the menu price lookup and the subtotal calculator have bugs. If the final receipt says $30 instead of $75, staring only at the adder at the bottom is confusing because one of the line items above was also priced at 1x instead of 3x. If you first save a copy of the original receipt, fix the lowest-level item calculation first, and re-print the receipt, each remaining discrepancy shrinks down to a single, obvious cause.
Jumping straight into editing code without running the full test suite first leaves you with no baseline — a recorded snapshot of which tests pass and fail before your changes — so you cannot tell if your edit caused a regression (breaking a feature that previously worked). Likewise, debugging top-level aggregation tests before fixing the low-level helper methods they call wastes time chasing compound arithmetic errors, and changing test assertions to make red tests turn green hides real production bugs instead of solving them.
Here is how the bottom-up workflow untangles the three failures on a concrete 4-transaction sample for 2024-03-01 ($10 Grocery = 10 pts, $20 Restaurant = 60 pts, $50 Travel on 2024-03-02 = skipped, $5 Gas = 5 pts; expected total = 75):
- Fix
MerchantResolvercrash: Adding anulland blank check at the top ofcategoryForstops theNullPointerExceptioncrash and returns"UNKNOWN"safely. - Fix
RewardsCalculator1xvs3xbug: Replacingtxn.category() == "Restaurant"with"Restaurant".equals(txn.category())fixes the$20Restaurant item from20points to60points. - Re-run
DailyPointsAggregatorand fix the loop bound: Re-running the daily test now reportsexpected <75> but was <70>instead of<30>. The missing5points matches the very last item ($5Gas at index3), exposingi < txns.size() - 1right away; switching tofor (Transaction txn : txns)yields10 + 60 + 5 = 75.
Key points
- Record a clean baseline first: Run every unit test (an automated check of one small method or class in isolation) via
mvn clean testor./gradlew clean testbefore editing anything so you know the exact pass/fail counts. - Distinguish assertion failures from crashes: An assertion failure means the code ran and returned the wrong number; an error means an uncaught exception crashed execution, and its stack trace (the chain of active method calls printed at the crash) points straight to the failing line in your production package.
- Debug from the lowest dependency upward: Fix leaf helpers (
MerchantResolver,RewardsCalculator) before callers (DailyPointsAggregator) so lower-level bugs stop polluting higher-level test outputs. - Understand Java string equality: Java uses string interning (reusing one shared memory object for identical hardcoded string literals), which hides
==reference-comparison bugs until a test passes a freshly parsedStringobject; always compare text with"Restaurant".equals(txn.category()). - Handle all forms of "missing" text: Guard against
null, empty"", and whitespace-only" "strings at the start of the method before calling.toUpperCase(Locale.ROOT)or querying maps that rejectnullkeys. - Eliminate manual index bounds where possible: An off-by-one error (iterating one element too few or too many, such as
i < list.size() - 1) disappears completely when you iterate withfor (Transaction txn : txns); for timestamp windows, use a half-open interval ([start, end), includingstartand excludingend) so midnight events are counted once. - Layer regression defenses afterward: Pair edge-case tests with
enumtypes, input normalization at boundaries, static analysis (automated tools like Error Prone or SpotBugs that scan source code for bug patterns without running it), and a focused code review checklist.
Common mistakes
- Editing production code before reproducing the failures: Without an initial clean run of the full suite, you cannot tell whether an unexpected failure was already broken or introduced by your fix.
- Modifying or disabling failing unit tests: Changing
assertEquals(75, ...)to70or adding@Disabledviolates the constraint and ships broken rewards logic to production. - Reading framework frames instead of project frames in a stack trace: Starting at JUnit or
jdk.internal.reflectlines wastes time; scan down to the firstcom.example...line you own. - Using
txn.category().equals("Restaurant")with the variable on the left: Iftxn.category()is evernull, calling.equalson it throws a newNullPointerException, whereas"Restaurant".equals(txn.category())safely evaluates tofalse. - Widening business rules silently with
equalsIgnoreCase: Unless the specification says categories are case-insensitive, stick to exact"Restaurant".equals(...)so your fix stays minimal and faithful to the contract. - Checking
merchantCode == nullwithout checking blank strings: Passing""or" "intocategoriesByCode.getOrDefault("", "UNKNOWN")can accidentally match a corrupt empty key or fail validation downstream. - Patching symptoms instead of root causes in aggregation: Adding
+ txns.get(txns.size() - 1)crashes on an empty list (IndexOutOfBoundsException) instead of fixing the loop condition itself.
Follow-up questions
- How should you proceed if a failing unit test appears to assert an outdated or incorrect business rule? Under a "do not modify tests" interview or ticket constraint, treat existing tests as the specification unless you can prove a direct contradiction with written product requirements or Javadoc. In real engineering work, document the exact discrepancy (for example, terms and conditions stating
2xpoints vs a test asserting3x), confirm the intended rule with the product owner or tech lead, and update the test in a separate, explicitly explained commit rather than slipping a silent test edit into a bug-fix PR. - What would you investigate if the daily points aggregation test failed intermittently or only in CI? A flaky test (a test that passes and fails intermittently without code changes) usually points to hidden dependence on wall-clock time, machine time zone, hash-map iteration order, or shared
staticstate left behind by an earlier test. For daily aggregation, CI servers typically run inUTCwhile laptops run in local time, so converting anInstantwithZoneId.systemDefault()shifts late-night transactions onto the next calendar day; fix it by passing an explicitZoneIdor injecting ajava.time.Clockinto the service. - How would you locate the exact breaking commit if this bug surfaced across a 500-commit release branch? Use
git bisect(a Git tool that binary-searches commit history by testing midpoints between a known good commit and a broken commit) to find the culprit in roughlylog2(500) ~= 9automated runs instead of checking commits one by one. Rungit bisect start HEAD <good-tag>followed bygit bisect runwith a tiny wrapper script that returns exit code125if compilation fails (telling Git to skip unbuildable commits) and otherwise runsmvn -Dtest=DailyPointsAggregatorTest test.
Follow-up questions
- How should you proceed if a failing unit test appears to assert an outdated or incorrect business rule?
- What would you investigate if the daily points aggregation test failed intermittently or only in CI?
- How would you locate the exact breaking commit if this bug surfaced across a 500-commit release branch?
Similar questions
- Auditable Loyalty Points Engine and Ledger
- Idempotent Card Rewards and Monthly Qualification Engine
- Enrich Card Transactions with Merchant Loyalty Points
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses