Behave BDD如何复用common_step.py中的步骤?求示例
在Behave BDD中传递步骤参数到anotherFile_steps.py
核心原理
Behave通过步骤定义中的占位符(如"{user}")捕获feature文件中的参数,并自动传递给对应的step函数。只要步骤的文本模式匹配,无论该step定义在哪个.py文件中,参数都会被正确传递。
场景1:复用公共步骤(无需修改anotherFile_steps.py)
如果common_step.py中已经定义了匹配的步骤,anotherFile_feature中的Given log in with "xyz" user会自动调用该步骤,参数"xyz"会被传递给user变量,不需要在anotherFile_steps.py中做任何额外操作。
common_step.py 已存在的代码:
from behave import given @given('log in with "{user}" user') def step_login_with_user(context, user): # 执行登录逻辑 print(f"登录用户:{user}") context.current_user = user
此时运行anotherFile_feature,Behave会自动执行上述步骤,user参数值为"xyz"。
场景2:在anotherFile_steps.py中重新实现步骤
如果需要针对anotherFile_feature定制登录逻辑,可以在anotherFile_steps.py中定义相同模式的步骤,Behave会优先使用该文件中的实现(根据加载顺序),参数依然自动传递。
anotherFile_steps.py 示例代码:
from behave import given @given('log in with "{user}" user') def step_login_with_user_another(context, user): # 针对当前feature的定制登录逻辑 print(f"为anotherFile_feature登录用户:{user}") context.current_user = user # 额外的定制操作,比如设置特定权限 context.user_permissions = "admin"
当运行anotherFile_feature时,Behave会调用这个定制步骤,user参数值为"xyz"。
验证参数传递
可以通过在step函数中添加断言来确认参数传递是否正确:
# 在step函数中添加验证 assert user == "xyz", f"预期用户为xyz,实际为{user}"
内容的提问来源于stack exchange,提问作者Ghazal Saeed
相关产品推荐
相关产品推荐

