pytest-bdd中能否用Then匹配When定义?支持多关键字复用吗?
pytest-bdd 步骤适配多关键字解决方案
方案一:给步骤函数添加多个关键字装饰器
直接用@given、@when、@then同时装饰同一个步骤函数,该步骤就能匹配场景中任意这些开头的关键字:
from pytest_bdd import given, when, then, parsers @given(parsers.parse('User downloads the file "{file_name}"')) @when(parsers.parse('User downloads the file "{file_name}"')) @then(parsers.parse('User downloads the file "{file_name}"')) def step_user_downloads_file(bdd_context, file_name): # 你的步骤逻辑 pass
pytest-bdd中的And关键字会自动继承前一个步骤的关键字类型(比如前一步是Then,And就等效于Then),所以覆盖三个核心关键字后,And也能正常匹配。
方案二:自定义通用装饰器简化代码
如果有大量步骤需要适配多关键字,可以写一个自定义装饰器,批量给函数添加所有关键字装饰,避免重复代码:
from pytest_bdd import given, when, then, parsers def step(parser): def decorator(func): # 依次添加三个关键字的装饰器 func = given(parser)(func) func = when(parser)(func) func = then(parser)(func) return func return decorator # 使用自定义装饰器定义步骤 @step(parsers.parse('User downloads the file "{file_name}"')) def step_user_downloads_file(bdd_context, file_name): # 你的步骤逻辑 pass
这样每个步骤只需要写一次装饰器,就能适配所有Given/When/Then/And关键字。
内容的提问来源于stack exchange,提问作者Roman Gelembjuk
相关产品推荐
相关产品推荐

