0
0
PyTesttesting~3 mins

Why Given-When-Then pattern in PyTest? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Want to write tests that tell a clear story anyone can follow?

The Scenario

Imagine testing a calculator app by clicking buttons and writing down results on paper every time you want to check if addition works.

The Problem

This manual way is slow and easy to mess up. You might forget steps or mix results, making it hard to trust your testing.

The Solution

The Given-When-Then pattern helps organize tests clearly: Given some setup, When an action happens, Then expect a result. It makes tests easy to read and follow.

Before vs After
Before
def test_add():
    result = add(2, 3)
    assert result == 5
After
def test_add():
    # Given two numbers
    a, b = 2, 3
    # When they are added
    result = add(a, b)
    # Then the result should be 5
    assert result == 5
What It Enables

This pattern makes tests clear and simple, so anyone can understand what is tested and why.

Real Life Example

When testing a login feature, you can say: Given a user with valid credentials, When they enter them and press login, Then they should see the homepage.

Key Takeaways

Manual testing is slow and error-prone.

Given-When-Then organizes tests into clear steps.

It improves test readability and trust.