PyTest报错ValueError: did not yield a value,fixture用yield遇问题求助
解决pytest fixture中
ValueError: did not yield a value报错的问题 你的代码存在两个核心问题导致报错:
- 在
with代码块里使用了return data,这会直接终止函数执行,后面的yield语句永远不会被执行,pytest检测到fixture函数没有产出值,就会抛出该错误。 - pytest的fixture如果采用
yield模式,不能同时使用return,两者只能二选一。
修正后的代码如下:
import pytest import json @pytest.fixture def names_resp(): with open('ropo_resp.json', 'r') as names: data = json.load(names) yield data # 用yield替代return,传递fixture数据给测试用例 print("a") # yield之后的代码为清理逻辑,测试用例执行完毕后自动运行
额外说明:
- 移除了不必要的
global data,fixture产出的数据可以直接被测试用例接收,无需全局变量。 - yield之前的代码是fixture的初始化逻辑,会在测试用例执行前运行;yield之后的代码是资源清理逻辑,会在测试用例执行完成后触发。
内容的提问来源于stack exchange,提问作者emboole
相关产品推荐
相关产品推荐

