0
0
Testing Fundamentalstesting~15 mins

Why white-box testing examines code internals in Testing Fundamentals - Automation Benefits in Action

Choose your learning style9 modes available
Verify white-box testing inspects code internals
Preconditions (2)
Step 1: Open the source code of the function 'calculate_discount' that applies a discount based on customer type
Step 2: Write a test that checks the function behavior for different customer types by inspecting internal logic branches
Step 3: Run the test and observe if all code paths are covered and verified
✅ Expected Result: The test should confirm that all internal branches of the function are tested and behave as expected
Automation Requirements - unittest
Assertions Needed:
assertEqual to verify function output for each input
assertTrue to confirm internal conditions if accessible
Best Practices:
Use clear and descriptive test method names
Test all logical branches inside the function
Keep tests independent and repeatable
Automated Solution
Testing Fundamentals
import unittest

# Function to test

def calculate_discount(customer_type, amount):
    if customer_type == 'regular':
        return amount * 0.9  # 10% discount
    elif customer_type == 'vip':
        return amount * 0.8  # 20% discount
    else:
        return amount  # no discount

class TestCalculateDiscount(unittest.TestCase):
    def test_regular_customer(self):
        self.assertEqual(calculate_discount('regular', 100), 90)

    def test_vip_customer(self):
        self.assertEqual(calculate_discount('vip', 100), 80)

    def test_unknown_customer(self):
        self.assertEqual(calculate_discount('guest', 100), 100)

if __name__ == '__main__':
    unittest.main()

This test script uses Python's unittest framework to check the calculate_discount function.

Each test method checks a different internal branch of the function: 'regular', 'vip', and unknown customer types.

Assertions verify the output matches expected discounts, ensuring the internal logic is tested.

This approach shows white-box testing by directly examining and validating the code's internal decision paths.

Common Mistakes - 3 Pitfalls
Testing only one input without covering all branches
Using print statements instead of assertions
Not isolating tests leading to dependencies
Bonus Challenge

Now add data-driven testing with 3 different customer types and amounts

Show Hint