0
0
PyTesttesting~10 mins

Given-When-Then pattern in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses the Given-When-Then pattern to check if a simple calculator adds two numbers correctly. It verifies that the sum is as expected.

Test Code - pytest
PyTest
import pytest

class Calculator:
    def add(self, a, b):
        return a + b

@pytest.fixture
def calculator():
    # Given: a calculator instance
    return Calculator()

def test_addition(calculator):
    # When: adding two numbers
    result = calculator.add(3, 4)
    # Then: the result should be 7
    assert result == 7, f"Expected 7 but got {result}"
Execution Trace - 3 Steps
StepActionSystem StateAssertionResult
1Test starts and pytest fixture creates a Calculator instanceCalculator object is ready for use-PASS
2Calls add method with inputs 3 and 4Calculator adds 3 + 4 internally-PASS
3Checks if the result equals 7Result is 7assert result == 7PASS
Failure Scenario
Failing Condition: The add method returns a wrong sum, e.g., 8 instead of 7
Execution Trace Quiz - 3 Questions
Test your understanding
What does the 'Given' step represent in this test?
ASetting up the calculator instance
BPerforming the addition
CChecking the result
DCleaning up after the test
Key Result
Using the Given-When-Then pattern helps organize tests clearly by separating setup, action, and verification steps, making tests easier to read and maintain.