Chapter 7: Testing and Debugging

Chapter 7: Testing and Debugging · Study Questions
Errors and failuresTest levelsJUnitLifecycleBoundary valuesRegressionTDDDebuggerassertCode coverageStatic analysisMemory
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Introduction

Question 1: Error, Defect, Failure

A programmer mistakenly chose 0 as the starting value in a method that finds the largest element of an array; when all temperatures were negative, “Highest: 0” appeared on screen. Which is the failure in this incident?

B: An error is the programmer's misunderstanding; a defect is the wrong line in the code that reflects this misunderstanding (int max = 0;); a failure is the wrong behavior seen while running. A test reveals the failure, debugging finds the defect, and the fix removes the error.

Multiple Choice · Test Types

Question 2: Which Level?

The Account subsystem expects dates as day/month/year, the database subsystem as year-month-day; each works correctly on its own, but together they create wrong records. Which test level catches this problem most directly?

C: A subsystem test checks the interfaces where subsystems meet (communication, data format). Unit tests check each part on its own; here both pass. A system test checks the whole system against functional and non-functional requirements, an acceptance test with the customer on real data; they catch the problem later and at higher cost.

Output Question · Unit Testing and JUnit

Question 3: Which Ones Pass?

JUnit 5 runs these five tests. Which ones pass (✔) and which fail (✘)? What causes the failures?

@Test void a() { assertEquals(new int[] {1, 2}, new int[] {1, 2}); }
@Test void b() { assertArrayEquals(new int[] {1, 2}, new int[] {1, 2}); }
@Test void c() { assertEquals(1.0 / 3, 0.333, 0.001); }
@Test void d() { assertSame(new String("x"), "x"); }
@Test void e() { assertEquals("x", new String("x")); }
Show answer
  • a ✘: assertEquals for arrays uses equals, which compares references: two separate arrays are not equal. The message shows that both arrays are [1, 2], but their addresses differ.
  • b ✔: assertArrayEquals compares element by element.
  • c ✔: |0,3333… − 0,333| ≈ 0,0003 ≤ 0,001.
  • d ✘: assertSame requires the same object (==); new String is a new object.
  • e ✔: assertEquals compares contents for Strings.

The calls were tried with JUnit 5.11's Assertions class.

Step-by-Step Trace · Unit Testing and JUnit

Question 4: Test Objects and a static Field

JUnit ran the tests in this class in the order t1, t2. What happens for each test, and what is the result? What would change if the order were reversed?

For t1 a new test object (#1) is created; its instance field n = 0. The static s belongs to the class, with a single copy.

@BeforeEach runs before every test.

n = 1: passes.

A brand-new object (#2) for t2: n starts from 0 again; s has stayed at 1.

@BeforeEach: s is 2, n is 1.

s = 2: fails. If the order were reversed, t2 would pass with s = 1 and t1 would pass too: the result depends on test order. Tests should not share static state; instance fields are reset for each test.

class OrderTest {
  static int s = 0;
  int n = 0;
  @BeforeEach
  void setUp() {
    s++;
    n++;
  }
  @Test
  void t1() {
    assertEquals(1, n);
  }
  @Test
  void t2() {
    assertEquals(1, s);
  }
}

Multiple Choice · Unit Testing and JUnit

Question 5: Subclass Exception

Integer.parseInt("abc") throws NumberFormatException. What happens to this test?

@Test
void letterNumber() {
  assertThrows(IllegalArgumentException.class,
      () -> Integer.parseInt("abc"));
}

D: assertThrows passes if the thrown exception is of the expected type or a subtype of it and returns the exception object (here NumberFormatException, with the message For input string: "abc"). If the exact type is required, assertThrowsExactly is used. A lambda can also be an expression that returns a value; the value is ignored.

Multiple Choice · Unit Testing and JUnit

Question 6: Lifecycle Counts

A test class has three @Test methods and one each of @BeforeAll, @BeforeEach, @AfterEach and @AfterAll methods. One of the tests fails. How many times do the @BeforeAll, @BeforeEach and @AfterEach methods run, respectively?

A: @BeforeAll (static) runs once before all tests. @BeforeEach and @AfterEach run once for each test; @AfterEach runs even if the test fails, which is why cleanup goes there. @AfterAll runs once at the very end.

Classic Question · Unit Testing and JUnit

Question 7: Boundary Values for a Ticket Price

Choose a set of test inputs for the method using boundary value analysis and write the expected result for each input.

static int ticket(int age) {
  if (age < 0 || age > 120)
    throw new IllegalArgumentException(
        "Invalid age: " + age);
  if (age < 7) return 0;
  if (age < 18) return 50;
  if (age >= 65) return 60;
  return 100;
}
Show answer
age−106717186465120121
expectedexception0050501001006060exception

The two ends of each range and the first values of the invalid region were chosen; errors most often appear at exactly these values, when < and <= are confused. Values in the same range, such as 30 and 40, are in the same equivalence class, so one is enough. Implementation: @ParameterizedTest + @CsvSource({"0, 0", "6, 0", "7, 50", …}) and for out-of-range input two assertThrows calls. The table was verified by running the method.

Spot the Bug · Unit Testing and JUnit

Question 8: The Leap Year Test Fails

A parameterized test checks this method. Which line fails and what message does JUnit give? Fix the defect.

static boolean isLeapYear(int y) {
  return y % 4 == 0 && y % 100 != 0;
}

@ParameterizedTest
@CsvSource({"2024, true", "1900, false",
            "2000, true", "2023, false"})
void leapYears(int year, boolean expected) {
  assertEquals(expected, isLeapYear(year));
}
Show answer
✔ [1] 2024, true
✔ [2] 1900, false
✘ [3] 2000, true
  expected: <true> but was: <false>
✔ [4] 2023, false

Defect: century years divisible by 400 (2000) are also leap years; the method forgets this rule. Fix:

return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;

If only 2024 and 2023 had been chosen, the tests would pass and the defect would stay hidden: 1900 and 2000 are the boundary cases of this rule.

Step-by-Step Trace · Unit Testing and JUnit

Question 9: Exception Inside a Test

BankAccount has withdraw, which for an amount greater than the balance throws IllegalStateException("Insufficient balance"). When this test runs, which lines run and what is the result?

Setup: the account is opened with 100.

deposit(50): 150.

The assertion passes; the test continues.

200 > 150: withdraw throws an exception. It is not caught in the test method, so the method ends here.

The final assertion and println never run: “done” is not printed. An unexpected exception fails the test. If the exception is the expected behavior, it is tested with assertThrows; testing a single behavior per test also pinpoints the location of the error.

@Test
void depositAndWithdraw() {
  BankAccount h = new BankAccount(100);
  h.deposit(50);
  assertEquals(150.0, h.getBalance(), 0.001);
  h.withdraw(200);
  assertEquals(-50.0, h.getBalance(), 0.001);
  System.out.println("done");
}

Multiple Choice · Regression and Automation

Question 10: A Flaky Test

Which of these tests can sometimes pass and sometimes fail with the same code (flaky)?

B: The unseeded new Random() produces a different number on every run: expecting a particular value will pass with probability 1/6 over time. A fixed seed (42) gives the same sequence every time, so the test is deterministic. Checking the 1–6 range is true for every die; two dice with the same seed also always give the same result.

Multiple Choice · Regression and Automation

Question 11: The TDD Cycle

In test-driven development (TDD), which is the correct order of steps for a feature?

C: TDD: red (a test that fails or does not compile for behavior that does not exist yet), green (the simplest code that passes), refactoring (cleaning the code while the tests protect the behavior). This way every line of code is born with a test, and regression tests accumulate on their own.

Step-by-Step Trace · Debugging

Question 12: Average with the Debugger

average returns 1.0 instead of 1.5 for {1, 2}. Stopped at the breakpoint on line 10, these commands are given: Step Into, Step Over, a breakpoint at line 7 + Resume, Evaluate, Step Out, Step Over. Where are we at each step and what are the variables?

Breakpoint: line 10 has not run yet.

Step Into: entered average; a new frame was added to the stack. t does not exist yet.

Step Over: t = 0 ran.

Resume: the loop ended, stopped at the new breakpoint. t = 3 is correct.

Evaluate: t / d.length = 1. Two ints are divided: integer division! Defect found; (double) t / d.length = 1.5.

Step Out: the method ended, returned 1 → 1.0; back in main, the assignment is about to complete.

Step Over: line 10 completed, o = 1.0; println is the next line. Before the fix, a unit test expecting {1, 2} → 1.5 is written; after the fix it turns green.

public class Avg {
  static double average(int[] d) {
    int t = 0;
    for (int v : d) {
      t += v;
    }
    return t / d.length;
  }
  public static void main(String[] args) {
    double o = average(new int[] {1, 2});
    System.out.println(o);
  }
}

Classic Question · Analysis Tools

Question 13: Line and Branch Coverage

For this method there is only the test assertEquals("low", category(5)). What are the line coverage (5 executable lines) and the branch coverage (2 conditions × true/false) as percentages? Which tests must be added for 100% branch coverage?

static String category(int t) {
  if (t < 0) {
    return "invalid";
  }
  if (t <= 10) {
    return "low";
  }
  return "high";
}
Show answer
  • category(5): t < 0 (false) → t <= 10 (true) → return "low". Line: 3 / 5 = 60% (return "invalid" and return "high" did not run).
  • Branch: the false branch of the 1st condition and the true branch of the 2nd: 2 / 4 = 50%.
  • To add: category(-1) → "invalid" (1st condition true) and category(20) → "high" (2nd condition false). 0 and 10 should also be added for the boundaries; even with 100% coverage, <= replaced by < is caught only by category(10).

Multiple Choice · Analysis Tools

Question 14: Found by Static Analysis

Which of these can a static analysis tool such as SpotBugs find without running the program

D: Static analysis inspects compiled code against patterns: ES_COMPARING_STRINGS_WITH_EQ, or a trim() whose result is unused. A profiler (JFR, VisualVM) shows where time is spent, a heap dump with Eclipse Memory Analyzer shows a filling heap, and Selenium tests show browser behavior; these require the program to run.

Output Question · Analysis Tools

Question 15: switch and -Xlint

What does the program print? javac -Xlint:all — which warnings does it give?

public class Sw {
  public static void main(String[] args) {
    int score = 2;
    String s = "";
    switch (score) {
      case 1: s += "a";
      case 2: s += "b";
      case 3: s += "c"; break;
      default: s += "d";
    }
    System.out.println(s);
  }
}
Show answer
bc

score = 2: execution enters at case 2, falls through to case 3 because there is no break: "b" + "c". The break in case 3 stops the fall into default.

Sw.java:7: warning: [fallthrough] possible fall-through into case
Sw.java:8: warning: [fallthrough] possible fall-through into case
2 warnings

Plain javac compiles without warnings; -Xlint reveals forgotten breaks without running the program.

Multiple Choice · Analysis Tools

Question 16: Why Isn't It Collected?

A server adds the 1 MB of data from every request to the static List<byte[]> cache list and never removes anything; after a while an OutOfMemoryError occurs. Why doesn't the garbage collector delete these arrays?

A: The GC deletes only unreachable objects. A static field lives until the end of the program; every array in the list is reachable from it, so none is collected: this is a memory leak in Java. In VisualVM the troughs after GC keep rising; Memory Analyzer's Leak Suspects report ties the heap dump to this list. Fix: remove data that is finished with, or use a size-limited cache.

The End

Chapter 7: Testing and Debugging: Study Questions
Lecture slides: Chapter 7: Testing and Debugging · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.