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

Python Behave如何从外部Excel文件读取Scenario Outline的测试示例数据

Python Behave 从Excel读取测试数据实现方案

1. 安装依赖库

首先安装Excel读取所需的第三方库,执行命令:
pip install pandas openpyxl

2. 修改Feature文件

原有Feature文件中的Scenario Outline仅保留Examples表头,无需写入测试数据,示例如下:

Scenario Outline: 浏览器测试
    When 我访问地址 <base>/<page>/<ordNumber>/<custName>
    Then 浏览器中包含客户编号 <custNumber>

    Examples:
     | base | page | ordNumber | custName | custNumber |

注意:Excel表头名称需要和上述占位符、表头名称完全一致,否则参数无法正常匹配

3. 编写动态加载与统计逻辑

在项目根目录下创建/修改environment.py文件,添加如下代码:

import pandas as pd

# 全局变量统计用例结果
total_pass = 0
total_fail = 0

def before_feature(context, feature):
    # 匹配需要加载Excel数据的场景,可根据实际场景名称调整
    for scenario in feature.scenarios:
        if scenario.name == "浏览器测试" and scenario.type == "scenario_outline":
            # 读取Excel文件,路径可根据实际存放位置调整
            df = pd.read_excel("examples.xls")
            # 遍历Excel行,注入到examples中
            for _, row in df.iterrows():
                scenario.examples[0].rows.append([
                    row["base"],
                    row["page"],
                    str(row["ordNumber"]),
                    row["custName"],
                    str(row["custNumber"])
                ])

def after_scenario(context, scenario):
    global total_pass, total_fail
    # 统计单条用例执行结果
    if scenario.status == "passed":
        total_pass +=1
    elif scenario.status == "failed":
        total_fail +=1

def after_all(context):
    # 所有用例执行完成后打印统计结果
    print("==========测试用例统计结果==========")
    print(f"总用例数:{total_pass + total_fail}")
    print(f"通过用例数:{total_pass}")
    print(f"失败用例数:{total_fail}")
    print("====================================")

4. 原有步骤定义复用

之前写的When、Then步骤实现代码无需任何修改,可直接正常接收注入的参数执行测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:54:02