White-Box Testing: From Code to Coverage

White-box testing uses knowledge of a program’s internal structure to select tests. You inspect the implementation, identify execution routes that matter, and choose inputs that exercise them. This is useful when a function contains decisions, early returns, or loops: several successful tests might repeatedly follow the same route while leaving other code untouched.

Let the code guide test selection

Begin by tracing the program’s control flow. Identify the statements that can execute and the outcomes of each decision. Then choose a structural target, such as executing every statement or taking both outcomes of every decision.


An input alone is not a complete test. Record the expected result and compare it with the observed result. A test oracle might be a requirement, an independently calculated value, or a trusted reference implementation. Copying the current implementation’s output into the expected result can preserve the very mistake you want to detect.



Measure what the suite executes

Coverage measures how many specified items a collection of tests exercises. Count distinct items reached across the entire suite, rather than adding the counts from individual tests: several tests may exercise the same item.


Coverage=Distinct items exercisedTotal specified items×100%\text{Coverage} = \frac{\text{Distinct items exercised}}{\text{Total specified items}}\times 100\%


The denominator depends on the selected measure.


Measure

Items counted

What full coverage establishes

Statement coverage

Specified executable statements

Every counted statement executed at least once

Decision-outcome branch coverage

True and false exits from each decision

Every counted decision outcome occurred at least once

Path coverage

Specified complete execution routes

Every route in the specified set was exercised


The examples here count assignments and returns as statement items, and true/false decision exits as branch items. Decision lines are not additional statement items in these calculations. Coverage tools may count other items, including unconditional graph edges, so inspect their reporting rules before comparing percentages.


Example: A rewards function adds five points for a VIP customer.


Python
def points(vip):
    total = 20       # S1
    if vip:          # D1
        total += 5   # S2
    return total     # S3


A decision either executes an increment or bypasses it before both routes reach the return statement.


One test with vip=True executes S1, S2, and S3. Its statement coverage is 3/3×100%=100%3/3\times100\%=100\%. However, it takes only the true exit of D1, giving 1/2×100%=50%1/2\times100\%=50\% decision-outcome branch coverage. A test with vip=False supplies the missing exit.

Read coverage evidence carefully

For the structured routines considered here, exercising every decision outcome also executes every statement, but executing every statement need not exercise every outcome. Furthermore, exercising both outcomes of a compound decision does not necessarily exercise every component condition both ways.


Full branch coverage also leaves some combinations of decisions untested. Loops can create arbitrarily many execution paths, while relationships between conditions can make some apparent paths impossible. Investigate an unreachable item and document the evidence rather than silently removing it from the denominator.



Use coverage to locate structural gaps, then select inputs that reach those gaps and check meaningful results. Execution and verification are separate obligations: reaching a statement tells you that it ran, not that its calculation was correct.

What to remember

  • Derive structural targets from the implementation.
  • Calculate coverage using distinct items across the suite.
  • State exactly what the coverage denominator counts.
  • Check expected results independently; coverage alone is insufficient.

Example: Closing a Warehouse Fee Coverage Gap

A warehouse’s packing specification starts the fee at 4 CAD, adds 3 CAD when package weight exceeds 8 kg, and adds 6 CAD for rush packing. The implementation is shown below. A coverage gap is a specified structural item that none of the current tests exercises.


Python
def packing_fee(weight_kg, rush):
    fee = 4              # S1
    if weight_kg > 8:    # D1
        fee = fee + 3    # S2
    if rush:             # D2
        fee = fee + 6    # S3
    return fee           # S4


Count only S1–S4 as statement items. For branch coverage, count the true and false exits of D1 and D2, excluding unconditional transitions. Inputs are ordered as (weight_kg, rush). The current suite contains (5, False) and (10, False).


Use the packing specification to check expected fees independently of the implementation.


a) Calculate the suite’s statement coverage, tracing the fees as a check.


First trace (5, False). The weight does not exceed 8 kg and rush packing is not requested. The expected fee is ________, matching the returned fee. This execution reaches S1 and S4.


Next trace (10, False). The weight exceeds 8 kg, so the fee increases by 3 CAD. The expected fee is ________, again matching the return. This execution reaches S1, S2, and S4.


Combine the reached statements without counting S1 and S4 twice. The union is S1, S2, and S4; S3 is missing. Therefore three of four statement items are covered.


Statement coverage=34×100%=75%\text{Statement coverage}=\frac{3}{4}\times100\%=75\%


The suite has 75% statement coverage.


b) Calculate decision-outcome branch coverage and identify its gap.


For (5, False), D1 evaluates false and D2 evaluates false. For (10, False), D1 evaluates true and D2 evaluates false.


Across the suite, D1 contributes ________ distinct outcomes, while D2 contributes ________ distinct outcome. Repeating D2-false does not increase coverage.


There are two decisions with two outcomes each, giving four branch items altogether.


Branch coverage=2+12×2×100%=75%\text{Branch coverage}=\frac{2+1}{2\times2}\times100\%=75\%


The suite has 75% decision-outcome branch coverage. Its missing branch item is D2-true.


c) Add the minimum number of tests needed to achieve 100% of both measures.


The missing statement S3 executes when D2 is true. Choose an input with rush packing requested, such as (6, True). D1 evaluates false, and D2 evaluates true, so this test reaches S3 and supplies the missing decision outcome.


Check the expected result using the specification. A 6 kg package receives no weight surcharge, but rush packing adds 6 CAD. The expected fee is ________.


Expected fee=4 CAD+6 CAD=10 CAD\text{Expected fee}=4\ \text{CAD}+6\ \text{CAD}=10\ \text{CAD}


The expanded suite covers S1–S4 and both outcomes of D1 and D2.


Statement coverage=44×100%=100%\text{Statement coverage}=\frac{4}{4}\times100\%=100\%


Branch coverage=44×100%=100%\text{Branch coverage}=\frac{4}{4}\times100\%=100\%


At least one additional test is necessary because the original suite has uncovered items, and this single test covers them. Add one test, (6, True), to reach 100% of both measures. The coverage result still does not prove the fee function correct for every input.

A notification service tests this function once with busy=True. Count only assignments and returns as statement items, and count the true and false exits of the if as branch items. Which coverage report is correct?


Python
def retry_delay(busy):
    delay = 2
    if busy:
        delay = delay + 3
    return delay


The returned delay is measured in seconds.

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A sensor routine is intended to add every integer reading in a list. In loop-boundary testing, you choose inputs that exercise zero, one, and several executions of a loop body. Trace the implementation below without correcting it.


Python
def total_readings(samples):
    n = len(samples)
    total = 0
    i = 0
    while i < n - 1:
        total = total + samples[i]
        i = i + 1
    return total


A flowchart shows initialization, a loop condition, an accumulation step, an index increment, and a return.


For each test, enter the exact integer number of loop-body executions and the returned total. Count executions of the body, rather than evaluations of the condition.

Input readingsLoop-body executionsReturned total
Empty list
9
4, 7
2, 5, 8, 11

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

An account service runs the following function with the two input triples shown below. Inputs are ordered as (active, paid, admin). Calculate the suite’s decision-outcome branch coverage as a percentage, to one decimal place.


Python
def access_level(active, paid, admin):
    level = 0
    if active:          # D1
        level = 1
        if paid:        # D2
            level = 2
    if admin:           # D3
        level = 3
    return level


  • Test 1: (True, True, False)
  • Test 2: (False, False, True)

Count the true and false exits of each labelled decision as separate branch items. Exclude unconditional transitions from the denominator.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice