Skip to content
BENIBIX Learn

Test Fixture

Development🧪 Testing & QualityTest Basics

Also known as Fixture, Fixtures, Test Setup, pytest Fixture

The setup a test starts from. It might be a sample user or a cart.

Think of it like

Think of it like setting the table for dinner. Each guest gets the same plate, fork and cup.

Example

Emma's fixture makes a cart with one mug. Ten tests use it, so none of them builds a cart by hand.

Why it matters

Tests that start from the same state give the same answer every time.

Definition

A test fixture is the setup a test needs before it runs. It might be a sample user, a cart with items or an empty database. Many tests share one fixture, so the setup is written once. After the test, the fixture can clean up what it made. Every test then starts from the same known state.

Example code

python
import pytest

@pytest.fixture
def cart():
    return Cart(items=["mug"])

def test_total(cart):
    assert cart.total() == 8
The fixture builds the cart once, and the test asks for it by name.
The fixture is the first box: a cart that holds one mug.

Common mistake

Sharing one fixture that tests change. One test's leftovers then break the next test.

Key takeaways

  1. 1
    Known start. Every test begins the same way.
  2. 2
    Write once. Many tests share one setup.
  3. 3
    Clean up after. Leave nothing for the next test.