0
0
Testing Fundamentalstesting~15 mins

Branch coverage in Testing Fundamentals - Build an Automation Script

Choose your learning style9 modes available
Test branch coverage for a simple function
Preconditions (2)
Step 1: Call the function with a value that makes the if condition true
Step 2: Verify the function returns the expected result for the true branch
Step 3: Call the function with a value that makes the if condition false
Step 4: Verify the function returns the expected result for the false branch
✅ Expected Result: Both branches of the function are executed and verified, ensuring full branch coverage
Automation Requirements - pytest
Assertions Needed:
Assert the function returns correct output for true branch input
Assert the function returns correct output for false branch input
Best Practices:
Use clear and descriptive test function names
Test each branch separately to ensure coverage
Keep tests independent and repeatable
Automated Solution
Testing Fundamentals
def is_positive(number: int) -> str:
    if number > 0:
        return "Positive"
    else:
        return "Non-positive"

import pytest

def test_is_positive_true_branch():
    result = is_positive(5)
    assert result == "Positive"

def test_is_positive_false_branch():
    result = is_positive(0)
    assert result == "Non-positive"
    result = is_positive(-3)
    assert result == "Non-positive"

The function is_positive has two branches: one for numbers greater than zero, and one for zero or less.

The first test test_is_positive_true_branch calls the function with a positive number to cover the true branch and asserts the output is "Positive".

The second test test_is_positive_false_branch calls the function with zero and a negative number to cover the false branch and asserts the output is "Non-positive".

This way, both branches are executed and verified, achieving full branch coverage.

Common Mistakes - 3 Pitfalls
Testing only one branch of the if-else statement
Using the same input value for all tests
Not using assertions to verify output
Bonus Challenge

Now add data-driven testing with 3 different inputs to cover branches

Show Hint