如何解决pytest-bdd中的StepDefinitionNotFoundError错误
解决pytest-bdd的StepDefinitionNotFoundError错误
问题根源
- Feature文件路径引用错误:步骤文件中
@scenario指定的是./x.feature,但实际存在的feature文件是a.feature,导致pytest加载了错误的文件。 - Step定义语法错误:Scenario Outline中的参数
<thing>和<position>在Step定义里不能直接使用,需要用pytest-bdd支持的参数占位符语法,才能匹配Examples中传入的具体值。
修正后的代码
步骤文件a.py(/tmp/a.py)
from pytest_bdd import ( given, scenario, then, when, ) # 修正feature文件路径为实际的a.feature @scenario('./a.feature', 'Some outline') def test_some_outline(): """Some outline.""" @given('something') def something(): """something.""" pass # 使用带类型标记的参数占位符,匹配Examples中的整数参数 @when('{thing:d} is moved to {position:d}') def thing_is_moved_to_position(thing, position): assert isinstance(thing, int) assert isinstance(position, int) @then('something else') def something_else(): """something else.""" pass
验证方法
在/tmp目录下重新执行命令:
pytest ./a.py
补充说明
- 如果参数是字符串类型,可去掉占位符后的
:d,直接使用{thing}和{position},pytest-bdd会自动完成类型转换。
内容的提问来源于stack exchange,提问作者Charley
相关产品推荐
相关产品推荐

