0
0
Testing Fundamentalstesting~15 mins

Black-box vs white-box testing in Testing Fundamentals - Automation Approaches Compared

Choose your learning style9 modes available
Automate testing for a simple calculator add function using black-box and white-box approaches
Preconditions (2)
Step 1: Call add(2, 3) and verify the result is 5 (black-box test)
Step 2: Call add(-1, 1) and verify the result is 0 (black-box test)
Step 3: Review the add function code to confirm it returns a + b (white-box test)
Step 4: Write a test that covers the internal logic of add function explicitly (white-box test)
✅ Expected Result: All tests pass confirming correct addition behavior and code logic
Automation Requirements - pytest
Assertions Needed:
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
Best Practices:
Use clear test function names indicating black-box or white-box
Keep tests independent and simple
Use assert statements for validation
Document test purpose in comments
Automated Solution
Testing Fundamentals
import pytest

# Simple calculator add function

def add(a: int, b: int) -> int:
    return a + b

# Black-box tests: test only inputs and outputs

def test_add_black_box_positive():
    # Test adding positive numbers
    assert add(2, 3) == 5

def test_add_black_box_negative_and_positive():
    # Test adding negative and positive number
    assert add(-1, 1) == 0

def test_add_black_box_zeros():
    # Test adding zeros
    assert add(0, 0) == 0

# White-box test: test internal logic explicitly

def test_add_white_box_logic():
    # Since add is a simple return of a + b, test with multiple values
    for a, b in [(10, 5), (-3, -7), (0, 4)]:
        expected = a + b
        result = add(a, b)
        assert result == expected, f"Expected {expected} but got {result}"

if __name__ == "__main__":
    pytest.main()

The add function is a simple addition returning a + b.

Black-box tests test_add_black_box_positive, test_add_black_box_negative_and_positive, and test_add_black_box_zeros check the function output for given inputs without looking at the code.

The white-box test test_add_white_box_logic runs multiple inputs and compares the result to the expected sum, explicitly verifying the logic inside the function.

Using pytest allows simple assert statements and easy test running.

Each test is independent and clearly named to show if it is black-box or white-box testing.

Common Mistakes - 4 Pitfalls
Not using assert statements properly
Mixing black-box and white-box tests without clear separation
Testing only positive cases and ignoring edge cases
Hardcoding expected results without calculation
Bonus Challenge

Now add data-driven testing with 3 different input pairs for the add function

Show Hint