0
0
PyTesttesting~15 mins

Given-When-Then pattern in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify addition of two numbers using Given-When-Then pattern
Preconditions (2)
Step 1: Given two numbers 3 and 5
Step 2: When they are added
Step 3: Then the result should be 8
✅ Expected Result: The test passes confirming the sum is correct
Automation Requirements - pytest
Assertions Needed:
Assert the sum of the two numbers equals 8
Best Practices:
Use clear Given-When-Then comments or structure in the test
Keep test simple and readable
Use assert statements for verification
Automated Solution
PyTest
import pytest

# Test function following Given-When-Then pattern
def test_add_two_numbers():
    # Given two numbers
    num1 = 3
    num2 = 5

    # When they are added
    result = num1 + num2

    # Then the result should be 8
    assert result == 8, f"Expected sum to be 8 but got {result}"

This test uses the Given-When-Then pattern to organize the steps clearly.

Given: We set two numbers num1 and num2.

When: We perform the addition operation.

Then: We assert the result equals 8 using assert. This makes the test easy to read and understand.

Common Mistakes - 3 Pitfalls
Not separating Given, When, Then steps clearly
Using print statements instead of assert for verification
Hardcoding expected result without explanation
Bonus Challenge

Now add data-driven testing with 3 different pairs of numbers and their expected sums

Show Hint