0
0
PyTesttesting~5 mins

Given-When-Then pattern in PyTest

Choose your learning style9 modes available
Introduction

The Given-When-Then pattern helps us write clear and simple tests by breaking them into three easy steps: setup, action, and check.

When you want to test a feature step-by-step like a story.
When you want your tests to be easy to read and understand by anyone.
When you want to organize your test code clearly into preparation, action, and verification.
When you want to explain what your test does in simple language.
When you want to follow a common style used in behavior-driven testing.
Syntax
PyTest
def test_example():
    # Given: set up initial state
    # setup_code

    # When: perform the action
    # action_code

    # Then: check the result
    assert condition

Each section starts with a comment to explain the step.

Use clear and simple code in each step to keep tests readable.

Examples
This test checks if adding 2 and 3 gives 5.
PyTest
def test_addition():
    # Given: two numbers
    a = 2
    b = 3

    # When: we add them
    result = a + b

    # Then: the result is correct
    assert result == 5
This test verifies that appending 'apple' works on an empty list.
PyTest
def test_list_append():
    # Given: an empty list
    items = []

    # When: we add an item
    items.append('apple')

    # Then: the list has one item
    assert items == ['apple']
Sample Program

This test checks that the upper() method converts a string to uppercase correctly.

PyTest
def test_string_upper():
    # Given: a lowercase string
    text = 'hello'

    # When: we convert it to uppercase
    result = text.upper()

    # Then: the result is uppercase
    assert result == 'HELLO'

# To run this test, use: pytest filename.py
OutputSuccess
Important Notes

Use comments to clearly separate Given, When, Then steps.

Keep each step focused: setup only in Given, action only in When, checks only in Then.

Readable tests help others understand and maintain your code easily.

Summary

Given-When-Then breaks tests into setup, action, and check steps.

This pattern makes tests easy to read and understand.

Use clear comments and simple code in each step.