A step-by-step bug hunting routine
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's delivery fee is wrong "sometimes", and nobody can say when. Changing code at random wastes hours. A fixed routine turns "it is broken somewhere" into one line you can fix.
Reproduce the bug reliably
A reproduction is the exact steps and input that make a bug happen every time. A bug you can trigger on demand is half solved.
Example 1 turns "sometimes the fee is wrong" into five fixed times. The time is passed in as a parameter instead of calling LocalTime.now() inside the method, so the bug fails the same way on every run.
Example 1 · Turning "sometimes" into every time
import java.time.LocalTime;
public class FlashSaleRepro { // Flash sale rule: delivery costs Rs 10 from 4:00 pm to 5:59 pm; otherwise Rs 15 static int deliveryFee(LocalTime time) { if (time.getHour() > 16 && time.getHour() < 18) { return 10; } return 15; }
static void check(String time, int expected) { int actual = deliveryFee(LocalTime.parse(time)); String result = actual == expected ? "PASS" : "FAIL"; System.out.println(result + " " + time + " expected Rs " + expected + ", got Rs " + actual); }
public static void main(String[] args) { // The report said "sometimes the flash sale delivery fee is not applied". // Fixing the time as an input makes "sometimes" happen every time. check("15:59", 15); check("16:00", 10); check("16:30", 10); check("17:59", 10); check("18:00", 15); }}PASS 15:59 expected Rs 15, got Rs 15 FAIL 16:00 expected Rs 10, got Rs 15 FAIL 16:30 expected Rs 10, got Rs 15 PASS 17:59 expected Rs 10, got Rs 10 PASS 18:00 expected Rs 15, got Rs 15
What this code does
- Inside the real app the price used the current time, so the bug appeared only between 4:00 and 4:59 pm. With the time as a parameter, five fixed times reproduce it on every run.
- The two FAIL lines are both in the 16:xx hour, which already points at the cause:
getHour() > 16excludes hour 16.
"Sometimes" usually means a hidden input: the time of day, today's date, random numbers, the order of items, data from another user. Make that input explicit. A bug you cannot trigger is guesswork, and you cannot even tell whether a fix worked.
Narrow it down: inputs, layers, divide and conquer, git bisect
git bisect is a Git command that does a binary search through your commits: you mark one good and one bad commit, Git checks out the middle one, and you mark it, until the first bad commit is found.
Narrowing down means making the failing case smaller until only the cause is left: less input, fewer layers, fewer commits. Each step halves the space where the bug can hide. Example 2 does it for a list of 16 order lines.
git bisect startgit bisect bad # the commit you are on has the buggit bisect good v1.1.0 # this release did not# Git checks out a commit in the middle. Test it, then tell Git:git bisect good # or: git bisect bad# ...repeat until Git prints "<hash> is the first bad commit"git bisect reset # back to where you startedExample 2 · Divide and conquer on the input
import java.util.List;
public class ShrinkInputDemo { // Average price per unit of each order line: price / quantity static int averageUnitPrice(List<int[]> lines) { int sum = 0; for (int[] line : lines) { sum += line[0] / line[1]; } return sum / lines.size(); }
static boolean fails(List<int[]> lines) { try { averageUnitPrice(lines); return false; } catch (ArithmeticException e) { return true; } }
static String show(List<int[]> lines) { StringBuilder sb = new StringBuilder(); for (int[] line : lines) { sb.append(sb.length() == 0 ? "" : " ").append(line[0]).append("/").append(line[1]); } return sb.toString(); }
public static void main(String[] args) { List<int[]> lines = List.of( new int[] {499, 1}, new int[] {2598, 2}, new int[] {1197, 3}, new int[] {650, 1}, new int[] {899, 1}, new int[] {4998, 2}, new int[] {1899, 1}, new int[] {398, 2}, new int[] {849, 0}, new int[] {2199, 1}, new int[] {17999, 1}, new int[] {1299, 1}, new int[] {798, 2}, new int[] {650, 1}, new int[] {1797, 3}, new int[] {399, 1});
List<int[]> failing = lines; System.out.println(failing.size() + " lines: " + (fails(failing) ? "fails" : "passes")); while (failing.size() > 1) { int mid = failing.size() / 2; List<int[]> left = failing.subList(0, mid); List<int[]> right = failing.subList(mid, failing.size()); boolean leftFails = fails(left); System.out.println(" first " + left.size() + ": " + (leftFails ? "fails" : "passes") + ", last " + right.size() + ": " + (fails(right) ? "fails" : "passes")); failing = leftFails ? left : right; } System.out.println("Smallest failing input: " + show(failing)); }}16 lines: fails first 8: passes, last 8: fails first 4: fails, last 4: passes first 2: fails, last 2: passes first 1: fails, last 1: passes Smallest failing input: 849/0
What this code does
failsruns the method and reports whether it still throws. Each round keeps the half that fails, so 16 lines need only four rounds.- The smallest failing input is
849/0: an order line with quantity 0 (an out-of-stock mouse) makesprice / quantitydivide by zero. Now the fix is obvious; with 16 lines it was not.
Three ways to halve the problem:
- Inputs: remove half the input and test again; keep the half that still fails (Example 2). Ten halvings shrink 1000 rows to one.
- Layers: check the value at each boundary. Does the controller get the right request? Does the service return the right result? Does the repository run the right SQL? The bug is between the last right value and the first wrong one.
- Commits: if it worked in an older version,
git bisecthalves the range each time, andgit bisect run ./mvnw -q test -Dtest=FlashSaleTesteven runs a test for you on every step.
Predict the output
Halve the failing input
Eight rows fail, and you test the halves one at a time.
Round 1 of 2
You test rows 1 to 4 alone, and they pass. Where is the bug?
Form a hypothesis and test it with the debugger or a log
A hypothesis is one specific, testable guess about the cause of a bug, such as "the coupon is applied twice". It predicts something you can check.
In Example 3 the total for a Rs 1798 cart with FEST20 is Rs 1192, not Rs 1479. The hypothesis is that the coupon is applied twice. A log line in applyCoupon tests it in one run.
Example 3 · Testing one hypothesis with a log line
public class CouponHypothesis { static int couponCalls = 0;
static int applyCoupon(int amount, String code) { couponCalls++; System.out.println("LOG applyCoupon(" + amount + ", " + code + ") call " + couponCalls); return code.equalsIgnoreCase("FEST20") ? amount - amount * 20 / 100 : amount; }
static int subtotal(int[] prices, String code) { int sum = 0; for (int price : prices) { sum += price; } return applyCoupon(sum, code); }
static int total(int[] prices, String code, int delivery) { return applyCoupon(subtotal(prices, code), code) + delivery; }
public static void main(String[] args) { // Expected: (499 + 1299) - 20% = 1439, plus Rs 40 delivery = 1479 // Hypothesis: the coupon is applied twice. Experiment: log every call. System.out.println("Total: Rs " + total(new int[] {499, 1299}, "fest20", 40)); }}LOG applyCoupon(1798, fest20) call 1 LOG applyCoupon(1439, fest20) call 2 Total: Rs 1192
What this code does
- The LOG lines prove the hypothesis:
applyCouponruns once insidesubtotaland again insidetotal, so 20% is taken off twice (1798 → 1439 → 1152, plus 40 delivery). - The fix is to apply the coupon in one place only (Practice 3). The log line is removed afterwards; it was an experiment, not part of the program.
Test a hypothesis with one experiment whose result proves it right or wrong: a breakpoint, a watch, Evaluate Expression or a temporary log line. "Something is wrong with discounts" is not a hypothesis. "The coupon is applied twice" is, because it predicts two calls to applyCoupon.
Find the bug
Find the line
Each hypothesis points at one line. Find it.
Hypothesis: the coupon is applied twice. Which line applies it the first time?
Round 1 of 2Fix with a failing test first and check for the same bug elsewhere
A regression test is a test that reproduces a bug that was fixed, so if the bug ever comes back, the test fails.
Example 4 keeps the reproduction from Example 1 as a regression check, and Example 5 writes the same checks as a JUnit 5 test. The test comes before the fix, and it must fail first.
Example 4 · The fix, with the reproduction kept as a regression check
import java.time.LocalTime;
public class FlashSaleFixed { static final LocalTime FLASH_START = LocalTime.of(16, 0); static final LocalTime FLASH_END = LocalTime.of(18, 0); // not included
static boolean isFlashSale(LocalTime time) { return !time.isBefore(FLASH_START) && time.isBefore(FLASH_END); }
static int deliveryFee(LocalTime time) { return isFlashSale(time) ? 10 : 15; }
static int failures = 0;
static void check(String time, int expected) { int actual = deliveryFee(LocalTime.parse(time)); if (actual != expected) { failures++; } System.out.println((actual == expected ? "PASS" : "FAIL") + " " + time + " expected Rs " + expected + ", got Rs " + actual); }
public static void main(String[] args) { // The reproduction from Example 1 stays as a regression check check("15:59", 15); check("16:00", 10); check("16:30", 10); check("17:59", 10); check("18:00", 15); System.out.println(failures == 0 ? "All checks passed" : failures + " check(s) failed"); }}PASS 15:59 expected Rs 15, got Rs 15 PASS 16:00 expected Rs 10, got Rs 10 PASS 16:30 expected Rs 10, got Rs 10 PASS 17:59 expected Rs 10, got Rs 10 PASS 18:00 expected Rs 15, got Rs 15 All checks passed
What this code does
- The reproduction from Example 1 failed first; now the same five checks pass. Keeping them means a later edit that breaks 16:00 is caught at once.
isFlashSalecompares times withisBefore, so the start (16:00) is included and the end (18:00) is not, exactly as the rule says.
Example 5 · The same regression test in JUnit 5
Runs in: a Maven project with JUnit 5 (junit-jupiter 5.14.4) and a FlashSale class with the same deliveryFee method
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.LocalTime;
import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;
class FlashSaleTest {
@ParameterizedTest(name = "delivery at {0} costs Rs {1}") @CsvSource({"15:59, 15", "16:00, 10", "16:30, 10", "17:59, 10", "18:00, 15"}) void deliveryFeeFollowsTheFlashSaleRule(String time, int expected) { assertEquals(expected, FlashSale.deliveryFee(LocalTime.parse(time))); }}Before the fix (the test is written first and must fail): $ mvn test -Dtest=FlashSaleTest ... [ERROR] Tests run: 5, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: 0.068 s <<< FAILURE! -- in FlashSaleTest [ERROR] FlashSaleTest.deliveryFeeFollowsTheFlashSaleRule(String, int)[2] -- Time elapsed: 0.004 s <<< FAILURE! org.opentest4j.AssertionFailedError: expected: <10> but was: <15> ... [ERROR] Tests run: 5, Failures: 2, Errors: 0, Skipped: 0 [INFO] BUILD FAILURE After the fix: $ mvn test -Dtest=FlashSaleTest ... [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.052 s -- in FlashSaleTest [INFO] BUILD SUCCESS
What this code does
@ParameterizedTestwith@CsvSourceruns the same test for five times, one row each; the boundaries 15:59, 16:00, 17:59 and 18:00 are the rows that matter.- Run before the fix, rows 2 and 3 fail with
expected: <10> but was: <15>: the test reproduces the bug. After the fix all five pass, and the test stays in the project.
Watch the test fail for the right reason, then fix the code and watch it pass. A test that never failed proves nothing about this bug.
Then ask where else the same mistake can live. Search the code for the same pattern (Find in Files: Ctrl+Shift+F, or Cmd+Shift+F on a Mac, in both IntelliJ and VS Code), for example every other getHour() > 16. Better still, put the rule in one method, like isFlashSale, so the bug can exist in only one place.
Order of execution
Fix with a test first
Put the steps in the right order.
Next step
Check your understanding
12 quick questions