0
0
PyTesttesting~15 mins

Fixture as function argument in PyTest - Build an Automation Script

Choose your learning style9 modes available
Use pytest fixture as function argument to provide test data
Preconditions (2)
Step 1: Create a fixture named 'sample_data' that returns {'name': 'Alice', 'age': 30}
Step 2: Write a test function 'test_user_data' that accepts 'sample_data' as an argument
Step 3: Inside the test, assert that 'name' in sample_data equals 'Alice'
Step 4: Assert that 'age' in sample_data equals 30
Step 5: Run the test using pytest
✅ Expected Result: The test passes successfully, confirming the fixture data is correctly injected and assertions are true
Automation Requirements - pytest
Assertions Needed:
Assert sample_data['name'] == 'Alice'
Assert sample_data['age'] == 30
Best Practices:
Use pytest fixture decorator @pytest.fixture
Inject fixture by naming it as a test function argument
Keep fixture code separate from test logic
Use clear and descriptive fixture names
Automated Solution
PyTest
import pytest

@pytest.fixture
def sample_data():
    return {'name': 'Alice', 'age': 30}

def test_user_data(sample_data):
    assert sample_data['name'] == 'Alice'
    assert sample_data['age'] == 30

The @pytest.fixture decorator marks sample_data as a fixture that returns a dictionary.

The test function test_user_data accepts sample_data as an argument. Pytest automatically calls the fixture and passes its return value.

Assertions check that the data matches expected values. This confirms the fixture is correctly injected and used.

This separation keeps test data setup clean and reusable.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not using the fixture name as a test function argument', 'why_bad': "The fixture won't be injected automatically, so the test won't receive the data and may fail or error.", 'correct_approach': 'Name the test function argument exactly the same as the fixture name to enable automatic injection.'}
Defining fixture inside the test function
Returning mutable data from fixture and modifying it in test
Bonus Challenge

Now add data-driven testing with 3 different user data inputs using fixtures

Show Hint