The Given-When-Then pattern helps us write clear and simple tests by breaking them into three easy steps: setup, action, and check.
Given-When-Then pattern in PyTest
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
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
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
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.
Practice
1. What is the main purpose of the Given-When-Then pattern in pytest tests?
easy
Solution
Step 1: Understand the pattern roles
Given-When-Then divides a test into three parts: Given (setup), When (action), Then (check).Step 2: Match purpose with options
Only To organize tests into setup, action, and verification steps correctly describes this organization purpose.Final Answer:
To organize tests into setup, action, and verification steps -> Option BQuick Check:
Given-When-Then = organize test steps [OK]
Hint: Remember: Given=setup, When=action, Then=check [OK]
Common Mistakes:
- Thinking it only applies to UI tests
- Believing it skips setup steps
- Assuming no assertions are used
2. Which of the following is the correct way to write a Given-When-Then style pytest test function?
easy
Solution
Step 1: Check comment order and code logic
def test_example(): # Given x = 5 # When y = x + 3 # Then assert y == 8 correctly uses Given-When-Then comments in order with proper setup, action, and assertion.Step 2: Identify incorrect patterns
The other options either lack Given-When-Then comments or have them in the wrong order (e.g., When before Given).Final Answer:
def test_example():\n # Given\n x = 5\n # When\n y = x + 3\n # Then\n assert y == 8 -> Option AQuick Check:
Correct comment order = def test_example(): # Given x = 5 # When y = x + 3 # Then assert y == 8 [OK]
Hint: Follow comment order: Given, When, Then [OK]
Common Mistakes:
- Mixing the order of Given and When comments
- Skipping comments entirely
- Placing assertions outside Then step
3. Given the following pytest test using Given-When-Then pattern, what will be the test result?
def test_sum():
# Given
numbers = [1, 2, 3]
# When
total = sum(numbers)
# Then
assert total == 6medium
Solution
Step 1: Calculate sum of list
The sum of [1, 2, 3] is 1+2+3 = 6.Step 2: Check assertion correctness
The assertion checks total == 6, which is true, so test passes.Final Answer:
Test will pass because sum of [1, 2, 3] is 6 -> Option DQuick Check:
sum([1,2,3]) = 6 [OK]
Hint: Calculate sum and compare with assertion value [OK]
Common Mistakes:
- Assuming sum returns a list instead of number
- Thinking assertion expects a different value
- Confusing test error with failure
4. Identify the error in this Given-When-Then pytest test:
def test_multiply():
# Given
x = 4
y = 5
# When
result = x * y
# Then
assert result = 20medium
Solution
Step 1: Check assertion syntax
The assertion uses single '=' which is assignment, not comparison. It should be '==' for comparison.Step 2: Confirm other parts are correct
Variables and steps are correct; only assertion syntax is wrong.Final Answer:
Syntax error in assertion statement -> Option AQuick Check:
Use '==' in assert, not '=' [OK]
Hint: Use '==' for assert comparisons, not '=' [OK]
Common Mistakes:
- Using '=' instead of '==' in assert
- Confusing assignment with comparison
- Ignoring syntax errors in assertions
5. You want to test a function that filters out falsy values (like 0, '', None) from a list using Given-When-Then pattern in pytest. Which test code correctly applies this pattern and checks the result?
hard
Solution
Step 1: Verify Given-When-Then structure
def test_filter_falsy(): # Given data = [0, 1, '', 'hello', None, True] # When filtered = [x for x in data if x] # Then assert filtered == [1, 'hello', True] correctly uses Given for data setup, When for filtering action, Then for assertion check.Step 2: Check correctness of filtering and assertion
Filtering removes falsy values; expected list matches filtered result. Other options miss comments or have wrong assertion.Final Answer:
def test_filter_falsy():\n # Given\n data = [0, 1, '', 'hello', None, True]\n # When\n filtered = [x for x in data if x]\n # Then\n assert filtered == [1, 'hello', True] -> Option CQuick Check:
Given-When-Then + correct filter = def test_filter_falsy(): # Given data = [0, 1, '', 'hello', None, True] # When filtered = [x for x in data if x] # Then assert filtered == [1, 'hello', True] [OK]
Hint: Keep steps clear: setup, action, then check [OK]
Common Mistakes:
- Skipping Given-When-Then comments
- Asserting wrong filtered list
- Using filter object without converting to list
