如何在参数化测试中使用带params的pytest fixture?
解决方案
直接用pytest.fixture的params参数合并原有的两个fixture,同时保持类作用域,既不用手动声明多个fixture,也能达到相同的测试效果(4个用例通过、每个Thing实例仅初始化一次)。修改后的代码如下:
import pytest class Thing: def __init__(self, val) -> None: self.val = val print(f"Made a thing with val {val}", end=" ") # 用params参数生成多个fixture实例,保持类作用域 @pytest.fixture(scope="class", params=[1, 2]) def thing(request): return Thing(request.param) class TestThing: # 验证Thing的val属性,自动对应params中的每个值 def test_thing_val(self, thing, request): assert thing.val == request.param # 验证Thing实例存在,自动生成两个测试用例 def test_thing_useless(self, thing): assert thing
关键修改说明:
- 合并fixture:把原有的
thing1、thing2两个fixture替换为一个带params=[1,2]的thingfixture,pytest会自动为每个参数值生成对应的fixture实例。 - 保持类作用域:
scope="class"确保每个参数对应的Thing实例仅在TestThing类的所有测试执行前初始化一次,和原代码的fixture作用域行为完全一致。 - 简化测试函数:
test_thing_val直接依赖thingfixture,通过request.param获取当前fixture的参数值,验证val属性的正确性,自动生成2个测试用例。test_thing_useless直接依赖thingfixture,pytest会自动为每个参数值运行一次测试,生成2个测试用例,和原代码的参数化效果一致。
这样修改后,总共有4个测试用例,全部可以通过,且每个Thing实例仅初始化一次,完全匹配原代码的测试效果。
内容的提问来源于stack exchange,提问作者Zeke Marffy
相关产品推荐
相关产品推荐

