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

如何在Robot Framework中用Gherkin风格编写API测试用例(非Selenium)

在Robot Framework中实现无Selenium的BDD风格API测试

要实现类似Cucumber的BDD风格API测试,无需依赖Selenium,只需用Robot Framework核心功能搭配RequestsLibrary即可完成。以下是具体方案和代码示例:

所需依赖

  • Robot Framework:核心测试框架,原生支持Gherkin格式的Feature文件
  • RequestsLibrary:专门处理HTTP请求的库,用于和API交互,完全不需要Selenium

项目结构

建议按以下结构组织代码,保持用例和步骤定义分离:

api_bdd_test/
├── features/
│   └── user_management.feature  # BDD场景描述文件
├── step_definitions/
│   └── api_steps.robot          # 步骤逻辑实现文件
└── test_suite.robot             # 测试套件入口

1. 编写BDD Feature文件

在features/user_management.feature中,用Given/When/Then描述测试场景:

Feature: 用户管理API测试
  验证用户创建、查询接口的功能正确性

  Scenario: 创建新用户并验证查询结果
    Given 我准备好请求头为 {"Content-Type": "application/json"}
    When 我发送POST请求到 "/api/users" 并携带数据 {"name": "张三", "email": "zhangsan@example.com"}
    Then 响应状态码应为 201
    And 响应结果中包含键 "id"
    And 我发送GET请求到 "/api/users/{id}"
    Then 响应状态码应为 200
    And 响应结果中 "name" 字段的值为 "张三"

2. 实现步骤定义

在step_definitions/api_steps.robot中,将Feature里的自然语言步骤映射为可执行的Robot Framework关键字:

*** Settings ***
Library    RequestsLibrary
Variables  ${BASE_URL}    http://your-api-domain.com  # 替换为你的API实际地址

*** Keywords ***
我准备好请求头为
    [Arguments]    ${headers}
    Create Session    api_session    ${BASE_URL}    headers=${headers}

我发送POST请求到 ${endpoint} 并携带数据 ${payload}
    [Arguments]    ${endpoint}    ${payload}
    ${response}=    Post Request    api_session    ${endpoint}    json=${payload}
    Set Suite Variable    ${RESPONSE}    ${response}

我发送GET请求到 ${endpoint}
    [Arguments]    ${endpoint}
    # 动态替换路径中的{id}为创建用户返回的ID
    ${actual_endpoint}=    Replace String    ${endpoint}    {id}    ${RESPONSE.json()["id"]}
    ${response}=    Get Request    api_session    ${actual_endpoint}
    Set Suite Variable    ${RESPONSE}    ${response}

响应状态码应为 ${expected_status}
    [Arguments]    ${expected_status}
    Should Be Equal As Integers    ${RESPONSE.status_code}    ${expected_status}

响应结果中包含键 ${key}
    [Arguments]    ${key}
    Should Contain Key    ${RESPONSE.json()}    ${key}

响应结果中 ${field} 字段的值为 ${expected_value}
    [Arguments]    ${field}    ${expected_value}
    Should Be Equal    ${RESPONSE.json()[${field}]}    ${expected_value}

3. 编写测试套件入口

在test_suite.robot中引入步骤定义并指定要执行的Feature文件:

*** Settings ***
Resource    step_definitions/api_steps.robot
Test Template    RobotFrameworkBDD    features/user_management.feature

*** Test Cases ***
用户管理API测试套件
    # 框架会自动解析Feature文件并执行对应步骤

运行测试

先安装依赖:

pip install robotframework robotframework-requests

然后执行测试命令:

robot test_suite.robot

扩展说明

  • 可以根据需求添加更多关键字,比如处理API认证(如添加Token到请求头)、DELETE/PUT请求、响应体复杂断言等
  • 如果需要参数化测试,可以在Feature文件中使用Scenario Outline和Examples块

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:30:45