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:

  • calculatesTriplePointsForRestaurants
  • returnsUnknownWhenMerchantCodeMissing
  • aggregatesDailyPointsCorrectly

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 on merchantCode, 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

  1. 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.

    1. Run a clean build and full test suite so no stale .class files hide or fake a result:
    Maven:   mvn clean test
    Gradle:  ./gradlew clean test
    
    1. 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.
    2. 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"
    
    1. 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)
    
  2. 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. Compare expected and actual numerically — their ratio (300 vs 100 is 3x vs 1x) or difference often points straight to the skipped if branch 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 aggregatesDailyPointsCorrectly got 30 instead of 75, 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 DailyPointsAggregator calls RewardsCalculator, a restaurant-points bug inside RewardsCalculator also corrupts the daily total! Fixing MerchantResolver and RewardsCalculator first strips away downstream noise so DailyPointsAggregator shows only its own bug.

  3. Fix 1: Compare String contents with equals, not ==

    Open RewardsCalculatorTest.calculatesTriplePointsForRestaurants (line 31) first to read the specification. Suppose it parses a $100.00 (10000 cents) restaurant transaction from a CSV line and expects 300 points (3 points per dollar), but gets 100 (1 point per dollar). Now inspect RewardsCalculator.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 builds new Transaction(..., "Restaurant", ...) passes by accident, whereas Transaction.parse("2024-03-01,m-42,Restaurant,10000") slices out a brand-new String object 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 if line and check txn.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 equalsIgnoreCase unless the requirements specify case-insensitive categories — changing business rules beyond the spec can break tests that expect "restaurant" to be rejected. Re-run RewardsCalculatorTest: $100.00 now yields 300 points and passes.

  4. 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 returnsUnknownWhenMerchantCodeMissing defines 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 == null first prevents the NullPointerException.
    • Trimming once into normalized and checking normalized.isEmpty() catches both "" and " " on every Java version (Java 8+), and returning "UNKNOWN" early also protects immutable maps such as Map.of(...), which throw NullPointerException if getOrDefault is ever called with a null key.
    • Passing Locale.ROOT to toUpperCase avoids locale-dependent bugs (for instance, on a machine set to the Turkish locale, "i".toUpperCase() produces dotted "İ" instead of "I").

    Re-run MerchantResolverTest and RewardsCalculatorTest: both pass.

  5. Fix 3: Repair the off-by-one loop bound in DailyPointsAggregator

    Now re-run DailyPointsAggregatorTest.aggregatesDailyPointsCorrectly before 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 5 points (75 - 70 = 5) is the exact value of the last element at index 3! Open DailyPointsAggregator.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() is 4, valid indices are 0, 1, 2, 3. Writing i < txns.size() - 1 (i < 3) visits only 0, 1, 2 — a classic off-by-one error (stopping one step too early or too late). Even better than changing < txns.size() - 1 to < txns.size(), replace the manual index loop with an enhanced for loop 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 Instant or LocalDateTime window rather than LocalDate, check the boundary condition instead: using ts.isAfter(dayStart) drops transactions at exact midnight 00:00:00. Always use a half-open interval [dayStart, nextDayStart) written as !ts.isBefore(dayStart) && ts.isBefore(dayStart.plusDays(1)).)

  6. Verify zero regressions and review the diff

    Once all three targeted tests pass individually, verify the whole project systematically:

    1. Run a full clean build (mvn clean test or ./gradlew clean test): Confirm the summary now reads 47 tests run, 47 passed, 0 failed, 0 errors — matching the baseline count with zero regressions.
    2. Audit git status and git diff: Confirm that at most three production files changed, zero test files were modified, no temporary System.out.println statements remain, and every changed line directly fixes one verified root cause.
    3. Check single-item and empty-list safety mentally: With for (Transaction txn : txns), a 1-element list now processes element 0 (previously i < 0 skipped it completely!), and an empty list cleanly returns 0.
  7. 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 (@ParameterizedTest with @NullAndEmptySource and @ValueSource(strings = {" ", "\t"})) for missing merchant codes; test category strings constructed dynamically (new String("Restaurant")) so string interning never masks ==; and test daily aggregation with 0 items, 1 item, matching items at index 0 and index n - 1, and exact 00:00:00 / 23:59:59 day 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 a Transaction. Comparing enums works identically with ==, .equals, and switch, eliminating string-reference and typo bugs permanently.
    • Boundary validation and clear null contracts: Normalize strings and reject invalid state inside the Transaction constructor (or mark nullable parameters explicitly with @Nullable), so downstream calculators never have to guess whether fields can be null or 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: .equals on objects, null/blank input guards, collection and timestamp boundary inclusivity, explicit Locale.ROOT / ZoneId, and integer cents vs floating-point dollars.

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):

  1. Fix MerchantResolver crash: Adding a null and blank check at the top of categoryFor stops the NullPointerException crash and returns "UNKNOWN" safely.
  2. Fix RewardsCalculator 1x vs 3x bug: Replacing txn.category() == "Restaurant" with "Restaurant".equals(txn.category()) fixes the $20 Restaurant item from 20 points to 60 points.
  3. Re-run DailyPointsAggregator and fix the loop bound: Re-running the daily test now reports expected <75> but was <70> instead of <30>. The missing 5 points matches the very last item ($5 Gas at index 3), exposing i < txns.size() - 1 right away; switching to for (Transaction txn : txns) yields 10 + 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 test or ./gradlew clean test before 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 parsed String object; 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 reject null keys.
  • 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 with for (Transaction txn : txns); for timestamp windows, use a half-open interval ([start, end), including start and excluding end) so midnight events are counted once.
  • Layer regression defenses afterward: Pair edge-case tests with enum types, 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, ...) to 70 or adding @Disabled violates 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.reflect lines wastes time; scan down to the first com.example... line you own.
  • Using txn.category().equals("Restaurant") with the variable on the left: If txn.category() is ever null, calling .equals on it throws a new NullPointerException, whereas "Restaurant".equals(txn.category()) safely evaluates to false.
  • 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 == null without checking blank strings: Passing "" or " " into categoriesByCode.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 2x points vs a test asserting 3x), 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 static state left behind by an earlier test. For daily aggregation, CI servers typically run in UTC while laptops run in local time, so converting an Instant with ZoneId.systemDefault() shifts late-night transactions onto the next calendar day; fix it by passing an explicit ZoneId or injecting a java.time.Clock into 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 roughly log2(500) ~= 9 automated runs instead of checking commits one by one. Run git bisect start HEAD <good-tag> followed by git bisect run with a tiny wrapper script that returns exit code 125 if compilation fails (telling Git to skip unbuildable commits) and otherwise runs mvn -Dtest=DailyPointsAggregatorTest test.

Follow-up questions

Similar questions

More Bilt Rewards interview questions

All 4 Bilt Rewards questions →