You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pytest-bdd框架的Python类中定义步骤测试函数?

问题解决:在Python类中使用pytest-bdd定义步骤测试函数

你遇到的错误并非pytest-bdd不支持类内分组测试,而是类中定义的方法缺少必要的self参数,同时全局变量pytest.AMT的使用方式也不够规范。以下是修正方案:

错误核心原因

类中的方法必须以self作为第一个参数,包括被@scenario、@given、@when、@then装饰的所有函数,否则pytest无法识别方法的签名,导致收集测试用例失败。

修正后的代码

修改test_transaction.py如下:

from pytest_bdd import scenario, given, when, then, parsers

class TestWithdrawal:
    def setup_method(self):
        # 初始化实例属性,替代全局变量
        self.amt = 0

    @scenario('test.feature', 'Withdraw Money')
    def test_withdraw(self):
        # 添加self参数
        pass

    @given(
        parsers.cfparse(
            "I deposit ${amount:Number}",
            extra_types={"Number": int}
        ),
        target_fixture="initial_amount"
    )
    def initial_amount(self, amount):
        # 添加self参数
        return amount

    @when(
        parsers.cfparse(
            "I withdraw ${withdrawn_amount:Number}",
            extra_types={"Number": int}
        )
    )
    def withdraw_money(self, initial_amount, withdrawn_amount):
        # 添加self参数,使用实例属性存储金额
        self.amt = initial_amount - withdrawn_amount

    @then(
        parsers.cfparse(
            "I should only have ${leftover_amount:Number} left",
            extra_types={"Number": int}
        )
    )
    def leftover_money(self, leftover_amount):
        # 添加self参数
        assert self.amt == leftover_amount

关键修改点

  • 所有类内方法添加self作为第一个参数,符合Python类方法的语法规范
  • 用实例属性self.amt替代全局变量pytest.AMT,避免全局状态污染,同时保证每个测试实例的独立性
  • 通过setup_method方法初始化实例属性,确保每次测试前金额都重置为0

执行验证

运行命令:

pytest test_transaction.py

此时测试用例会被正常收集并执行,三个示例场景都会通过。

内容的提问来源于stack exchange,提问作者blue2609

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 19:50:17