ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

14、pytest像用参数一样使用fixture

2026/8/29 18:28:15 拓冰建站 浏览量
14、pytest像用参数一样使用fixture

官方实例

# content of test_fruit.py
import pytestclass Fruit:def __init__(self, name):self.name = nameself.cubed = Falsedef cube(self):self.cubed = Trueclass FruitSalad:def __init__(self, *fruit_bowl):self.fruit = fruit_bowlself._cube_fruit()def _cube_fruit(self):for fruit in self.fruit:fruit.cube()# Arrange
@pytest.fixture
def fruit_bowl():return [Fruit("apple"),Fruit("banana")]def test_fruit_salad(fruit_bowl):# Actfruit_salad = FruitSalad(*fruit_bowl)# Assertassert all(fruit.cubed for fruit in fruit_salad.fruit)

解读与实操

在基本级别上,测试函数通过将它们声明为参数来请求它们所需的fixture。

当pytest运行测试时,它会查看该测试函数中的参数,然后搜索与这些参数名称相同的fixture。一旦pytest找到它们,它就运行这些fixture,捕获它们返回的内容,并将这些对象作为参数传递给测试函数。

在这里插入图片描述

场景应用

fixture是pytest最强大的功能之一,随着深入接触,会发现fixture的便捷之处。