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

pytest-bdd仅Given步骤出现StepDefinitionNotFoundError的原因排查

pytest-bdd 抛出 StepDefinitionNotFoundError 的原因及解决

运行代码时出现如下错误:

pytest_bdd.exceptions.StepDefinitionNotFoundError: Step definition is not found: Given "I have an empty shopping cart

Feature 文件内容

Feature: Shopping Cart
              As a customer
              I want to add products to my shopping cart
  So that I can purchase them later

        Scenario Outline: Add products to the shopping cart
            Given I have an empty shopping cart
             When I add <product> to the cart
             Then the cart should contain <product> and shelf number is <shelf_num>

        Examples:
                  | product | shelf_num |
                  | Apples  | 5         |
                  | Bananas | 24        |
                  | Oranges | 11        |

步骤定义代码

scenarios('scenario_example_demo.feature') 

@pytest.fixture
def shopping_cart():
    return []

@given('I have an empty shopping cart')
def empty_shopping_cart(shopping_cart):
    assert len(shopping_cart) == 0

@when(parsers.parse('I add {product} to the cart'))
def add_product(shopping_cart, product):
    shopping_cart.append(product)

@then(parsers.parse('the cart should contain {product} and shelf number is {shelf_num}'))
def verify_cart_contents(shopping_cart, product,shelf_num):
    assert product in shopping_cart and int(shelf_num)>0

奇怪的是,把Feature文件和步骤代码中的Given替换成When后,代码就能正常运行。


问题根源

核心原因是步骤定义的加载顺序错误:
代码里scenarios('scenario_example_demo.feature')的调用放在了所有步骤定义最前面。pytest-bdd执行scenarios()时会立刻解析Feature文件里的步骤,尝试匹配对应的Python步骤定义,但此时@given装饰的I have an empty shopping cart步骤还没被Python解释器加载,所以会抛出找不到定义的错误。

换成When后能运行只是偶然的加载顺序巧合,并非正确解决思路。

解决办法

把scenarios()的调用移到所有步骤定义的后面,确保pytest-bdd扫描场景前,所有步骤定义都已加载完成:

@pytest.fixture
def shopping_cart():
    return []

@given('I have an empty shopping cart')
def empty_shopping_cart(shopping_cart):
    assert len(shopping_cart) == 0

@when(parsers.parse('I add {product} to the cart'))
def add_product(shopping_cart, product):
    shopping_cart.append(product)

@then(parsers.parse('the cart should contain {product} and shelf number is {shelf_num}'))
def verify_cart_contents(shopping_cart, product,shelf_num):
    assert product in shopping_cart and int(shelf_num)>0

# 移到所有步骤定义之后
scenarios('scenario_example_demo.feature') 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 19:41:20