apifox-test-scenario

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

测试场景建模

Test Scenario Modeling

前置条件:先阅读
../apifox-cli/SKILL.md
。若旧总入口与本 skill 的领域规则冲突,以当前 CLI help 和本 skill 为准。涉及单接口 case 时读取
../apifox-test-case/SKILL.md
,涉及执行/CI/报告边界时读取
../apifox-test-automation/SKILL.md
。环境和变量命令以当前 CLI help 为准。
具体命令参数以当前 CLI help 为准。创建和更新测试场景时重点处理步骤保存语义、导入/引用边界、变量传递、复杂步骤字段风险和运行验证边界。Agent 维护场景时优先使用导入/引用命令和
get --with-case-detail
回读真实结构,再做局部 update。
Prerequisites: Read
../apifox-cli/SKILL.md
first. If the old main entry conflicts with the domain rules of this skill, follow the current CLI help and this skill. Refer to
../apifox-test-case/SKILL.md
when single-interface cases are involved, and
../apifox-test-automation/SKILL.md
when execution/CI/report boundaries are involved. Environment and variable commands are subject to the current CLI help.
Specific command parameters are subject to the current CLI help. When creating and updating test scenarios, focus on processing step saving semantics, import/reference boundaries, variable transfer, complex step field risks and operation verification boundaries. When maintaining scenarios via Agent, prioritize using import/reference commands and
get --with-case-detail
to read back the real structure, then perform partial updates.

何时使用

When to Use

  • 创建或更新测试场景。
  • 设计多步骤自动化流程,例如登录 -> 创建资源 -> 查询 -> 断言 -> 清理。
  • 编排多种步骤类型、条件分支、循环、等待、脚本、数据库操作或外部程序。
  • 处理前置/后置操作、变量引用、变量提取、断言链路。
  • 排查场景步骤衔接失败、变量为空、步骤顺序错误、场景创建后前端展示异常。
  • Create or update test scenarios.
  • Design multi-step automated workflows, such as Login -> Create Resource -> Query -> Assert -> Cleanup.
  • Orchestrate multiple step types, conditional branches, loops, waits, scripts, database operations or external programs.
  • Handle pre/post operations, variable references, variable extraction, assertion chains.
  • Troubleshoot failures in step connection, empty variables, incorrect step order, abnormal front-end display after scenario creation.

不应使用

When Not to Use

  • 单个接口下的测试用例:转
    apifox-test-case
  • 只运行已有场景、套件或 CI 命令:转
    apifox-test-automation
  • 只查看报告:按当前 CLI help 使用
    test-report
    ;执行和报告边界参考
    apifox-test-automation
  • 只配置环境、变量、数据库连接:按当前 CLI help 使用 environment、variables、database-connection 等命令。
  • Test cases under a single interface: Switch to
    apifox-test-case
    .
  • Only run existing scenarios, suites or CI commands: Switch to
    apifox-test-automation
    .
  • Only view reports: Use
    test-report
    according to current CLI help; refer to
    apifox-test-automation
    for execution and report boundaries.
  • Only configure environments, variables, database connections: Use commands like environment, variables, database-connection according to current CLI help.

核心边界

Core Boundaries

概念CLI 资源说明
接口测试用例
test-case
绑定某个 endpoint 的 case,适合单接口验证
测试场景
test-scenario
多步骤流程编排,支持复杂步骤衔接
测试套件
test-suite
场景/用例集合与回归组织
环境
environment
提供 baseUrl、变量、服务配置
测试数据
test-data
场景或 case 的迭代数据来源
ConceptCLI ResourceDescription
Interface Test Case
test-case
Case bound to a specific endpoint, suitable for single-interface verification
Test Scenario
test-scenario
Multi-step workflow orchestration, supports complex step connections
Test Suite
test-suite
Collection of scenarios/cases and regression organization
Environment
environment
Provides baseUrl, variables, service configurations
Test Data
test-data
Iterative data source for scenarios or cases

命令入口

Command Entry

使用当前 CLI help 查询
test-scenario
的参数。
import-steps
add-ref
未必出现在顶层“可用命令”列表,但各自支持
--help
,可用于导入步骤和添加场景引用。
关键事实:
test-scenario create
只保存元数据。即使 create payload 里包含
steps
,步骤也不会在 create 阶段保存。正确流程是先 create 元数据,再
get --with-case-detail
,再用
import-steps
add-ref
test-scenario update --file
添加或修改 steps。
常见导入优先使用高层命令,不要手写复杂 HTTP 绑定结构。已验证的入口包括:
bash
apifox test-scenario import-steps <scenarioId> --project <projectId> --source endpoint --ids <endpointIds> --sync manual
apifox test-scenario import-steps <scenarioId> --project <projectId> --source test-case --endpoint <endpointId> --ids <testCaseIds> --sync manual
apifox test-scenario import-steps <scenarioId> --project <projectId> --source test-scenario --from-scenario <sourceScenarioId> --step-ids <stepIds>
apifox test-scenario add-ref <scenarioId> --project <projectId> --scenario <sourceScenarioId>
语义边界:
  • import-steps
    是复制/导入为当前场景自己的步骤。
  • add-ref
    是添加一个引用其它场景的步骤,不复制源场景内部步骤。
  • --sync manual
    是默认模式,适合导入后补业务参数、变量引用和断言。
  • --sync auto
    只适用于 endpoint/test-case 来源,表示随源接口定义或单接口用例自动同步;
    test-scenario
    来源不支持 auto。
  • CLI 是非交互式命令,不会缺 ID 时自动列出全量资源;缺 endpoint、case、scenario 或 step ID 时,跟随 agentHints 先 list/get 定位。
简化创建必须给完整必填参数,但这只会创建空场景。除非用户明确要占位场景,否则“创建自动化测试/场景”不能停留在空场景。
Use the current CLI help to query parameters for
test-scenario
.
import-steps
and
add-ref
may not appear in the top-level "Available Commands" list, but each supports
--help
and can be used to import steps and add scenario references.
Key Fact:
test-scenario create
only saves metadata. Even if
steps
are included in the create payload, the steps will not be saved during the create phase. The correct process is to first create metadata, then use
get --with-case-detail
, and then add or modify steps using
import-steps
,
add-ref
or
test-scenario update --file
.
Prioritize using high-level commands for common imports instead of writing complex HTTP binding structures manually. Verified entries include:
bash
apifox test-scenario import-steps <scenarioId> --project <projectId> --source endpoint --ids <endpointIds> --sync manual
apifox test-scenario import-steps <scenarioId> --project <projectId> --source test-case --endpoint <endpointId> --ids <testCaseIds> --sync manual
apifox test-scenario import-steps <scenarioId> --project <projectId> --source test-scenario --from-scenario <sourceScenarioId> --step-ids <stepIds>
apifox test-scenario add-ref <scenarioId> --project <projectId> --scenario <sourceScenarioId>
Semantic Boundaries:
  • import-steps
    copies/imports steps as part of the current scenario.
  • add-ref
    adds a step that references another scenario without copying the internal steps of the source scenario.
  • --sync manual
    is the default mode, suitable for supplementing business parameters, variable references and assertions after import.
  • --sync auto
    only applies to endpoint/test-case sources, indicating automatic synchronization with the source interface definition or single-interface test case; it is not supported for test-scenario sources.
  • CLI is a non-interactive command and will not automatically list all resources when IDs are missing; when endpoint, case, scenario or step IDs are missing, follow agentHints to first list/get to locate them.
Complete required parameters must be provided for simplified creation, but this will only create an empty scenario. Unless the user explicitly requests a placeholder scenario, "create automated test/scenario" cannot stop at an empty scenario.

场景建模标准流程

Standard Process for Scenario Modeling

  1. 明确业务目标:验证什么流程、成功条件是什么、失败如何清理。
  2. 确认 project、branch、environment。
  3. 列出涉及的 endpoint、case、环境变量、测试数据、数据库连接或脚本。
  4. 如果在 AI 分支或迭代分支创建场景,只调整场景本身时不需要先 pick 被引用接口或用例;只有要修改被引用接口、单接口用例或源场景本身时,才从主分支或对应来源迭代分支 pick 所需资源到当前分支。
  5. 如果已有相似场景,先
    test-scenario list/get
    读取作为模板。
  6. 用自然语言先设计步骤图,再转 JSON,不要边猜字段边写。
  7. 获取
    test-scenario-create
    schema 创建元数据。
  8. 创建后
    test-scenario get --with-case-detail
    回读完整结构。
  9. 导入已有资源时优先用
    import-steps
    add-ref
    ,不要直接手写复杂绑定字段。
  10. 导入后再次
    test-scenario get --with-case-detail
    ,确认步骤写入且 HTTP case/detail 展开正常。
  11. 导入 API definition 或 test-case 后,检查 params、headers、body、脚本变量是否只是 schema 示例值;需要业务值时再用
    test-scenario update --file
    补齐。
  12. 精细编辑时获取
    test-scenario-update
    schema,基于完整结构添加或修改 steps。
  13. cli-schema validate
    通过后 update,再
    test-scenario get --with-case-detail
    确认
    steps
    非空且结构正确。
test-scenario-update
schema 已包含步骤、前后置处理器、断言、提取变量和枚举值说明。首次编写 processor 时先看 schema,不要凭经验猜字段名、枚举值或旧格式。
  1. Clarify business objectives: What process to verify, what are the success conditions, how to clean up in case of failure.
  2. Confirm project, branch, environment.
  3. List involved endpoints, cases, environment variables, test data, database connections or scripts.
  4. If creating scenarios in AI branches or iterative branches, there is no need to pick referenced interfaces or cases first when only adjusting the scenario itself; only when modifying referenced interfaces, single-interface test cases or the source scenario itself, pick the required resources from the main branch or corresponding source iterative branch to the current branch.
  5. If there are similar existing scenarios, first use
    test-scenario list/get
    to read them as templates.
  6. Design the step diagram in natural language first, then convert it to JSON; do not write while guessing fields.
  7. Obtain the
    test-scenario-create
    schema to create metadata.
  8. After creation, use
    test-scenario get --with-case-detail
    to read back the complete structure.
  9. When importing existing resources, prioritize using
    import-steps
    or
    add-ref
    instead of writing complex binding fields directly.
  10. After import, use
    test-scenario get --with-case-detail
    again to confirm that steps are written and HTTP case/detail are expanded normally.
  11. After importing API definition or test-case, check if params, headers, body, script variables are only schema sample values; use
    test-scenario update --file
    to supplement them when business values are needed.
  12. When performing fine-grained editing, obtain the
    test-scenario-update
    schema and add or modify steps based on the complete structure.
  13. After passing
    cli-schema validate
    , perform the update, then use
    test-scenario get --with-case-detail
    to confirm that
    steps
    are non-empty and the structure is correct.
The
test-scenario-update
schema already includes descriptions of steps, pre/post processors, assertions, extracted variables and enumeration values. When writing processors for the first time, check the schema first instead of guessing field names, enumeration values or old formats based on experience.

步骤设计最佳实践

Best Practices for Step Design

设计每个步骤时都写清:
text
stepName: 这一步做什么
stepType: 使用哪类步骤
input: 请求、脚本、SQL、等待条件或引用变量
output: 提取哪些变量
dependsOn: 依赖哪些上游步骤输出
assertions: 成功条件
onError: 失败后继续、停止或清理
cleanup: 是否需要后置清理
复杂流程建议分层:
text
准备数据
鉴权/登录
主流程操作
结果查询与断言
副作用校验
清理资源
When designing each step, clearly write:
text
stepName: What this step does
stepType: Which type of step to use
input: Request, script, SQL, wait condition or referenced variable
output: Which variables to extract
dependsOn: Which upstream step outputs to depend on
assertions: Success conditions
onError: Continue, stop or clean up after failure
cleanup: Whether post-cleanup is needed
Complex workflows are recommended to be layered:
text
Prepare Data
Authentication/Login
Main Process Operations
Result Query and Assertion
Side Effect Verification
Clean Up Resources

数据传递和变量引用

Data Transfer and Variable References

  • 创建前列出数据来源:环境变量、全局变量、前置步骤请求/响应、迭代数据、脚本输出。
  • 步骤间传递数据优先考虑 Apifox 原生“读取前置步骤的运行结果”,例如
    {{$.1.response.body.token}}
    {{$.2.response.body.data.id}}
    ;它只在自动化测试场景中生效,需要运行完整场景,单独运行某个步骤无法取值。
  • 同一数据需要多次引用、跨模块复用,或希望命名更稳定时,使用后置操作的提取变量,再用
    {{token}}
    等变量引用。
  • 随机后缀、临时标识符、跨步骤生成但不来自响应的数据,适合写入环境变量,例如
    pm.environment.set('runSuffix', suffix);
  • 在脚本中使用前置步骤结果时,不要直接写
    {{...}}
    ;使用
    pm.variables.get("$.1.response.body.token")
  • 步骤引用依赖步骤 ID/number,插入、删除、重排步骤后必须同步检查
    {{$.步骤号...}}
    是否仍指向正确步骤。
  • 不要假设响应路径一定是
    body.data.id
    ;先根据真实响应确认路径,例如
    {{$.2.response.body.id}}
    {{$.2.response.body.data.id}}
    {{$.2.response.body.data[0].id}}
  • 生成 payload 时必须原样保留
    {{...}}
    占位符,不要转义、拆分或改写,否则运行时无法替换。
  • 变量为空时,优先检查是否运行完整场景、步骤 ID、JSONPath、响应结构、步骤执行顺序和环境选择。
  • 这些步骤间传递、
    {{$.步骤号...}}
    forEach
    规则只适用于
    test-scenario
    ,不要写入单接口
    test-case
列表响应可作为
forEach.parameters.array
,循环内用当前元素引用后续字段:
json
{
  "type": "forEach",
  "parameters": {
    "array": "{{$.1.response.body}}",
    "disableOnError": false
  }
}
循环子步骤中引用当前元素:
{{$.2.element.id}}
。如果默认取数组第一个元素,要显式写出索引,例如
{{$.7.response.body.data[0].id}}
;如果业务要求特定元素,先筛选,不要假设列表顺序稳定。
  • List data sources before creation: Environment variables, global variables, pre-step request/response, iterative data, script output.
  • Prioritize using Apifox's native "read operation results of pre-steps" for data transfer between steps, such as
    {{$.1.response.body.token}}
    ,
    {{$.2.response.body.data.id}}
    ; it only takes effect in automated test scenarios and requires running the complete scenario, and cannot take values when running a single step alone.
  • When the same data needs to be referenced multiple times, reused across modules, or you want a more stable name, use the extract variable in post-operations, then reference it with variables like
    {{token}}
    .
  • Random suffixes, temporary identifiers, data generated across steps but not from responses are suitable for writing to environment variables, such as
    pm.environment.set('runSuffix', suffix);
    .
  • When using pre-step results in scripts, do not directly write
    {{...}}
    ; use
    pm.variables.get("$.1.response.body.token")
    .
  • Steps reference dependent step IDs/numbers; after inserting, deleting or rearranging steps, you must synchronously check whether
    {{$.stepNumber...}}
    still points to the correct step.
  • Do not assume that the response path must be
    body.data.id
    ; confirm the path based on the real response first, such as
    {{$.2.response.body.id}}
    ,
    {{$.2.response.body.data.id}}
    ,
    {{$.2.response.body.data[0].id}}
    .
  • When generating payloads, you must retain the
    {{...}}
    placeholders as they are; do not escape, split or rewrite them, otherwise they cannot be replaced during operation.
  • When variables are empty, prioritize checking whether the complete scenario is run, step ID, JSONPath, response structure, step execution order and environment selection.
  • These rules for inter-step transfer,
    {{$.stepNumber...}}
    and
    forEach
    only apply to
    test-scenario
    ; do not write them into single-interface
    test-case
    .
List responses can be used as
forEach.parameters.array
, and current elements are referenced in subsequent fields within the loop:
json
{
  "type": "forEach",
  "parameters": {
    "array": "{{$.1.response.body}}",
    "disableOnError": false
  }
}
Reference the current element in loop sub-steps:
{{$.2.element.id}}
. If the first element of the array is taken by default, explicitly write the index, such as
{{$.7.response.body.data[0].id}}
; if the business requires a specific element, filter it first and do not assume the list order is stable.

步骤内容和处理器结构

Step Content and Processor Structure

Apifox CLI 不会自动格式化场景内容,写入什么字符串,客户端就展示什么字符串。写入前先预格式化字符串字段:
  • 接口 Body:
    requestBody.data
  • 脚本内容:
    parameters.data
  • 前置/后置脚本:
    preProcessors[*].data
    postProcessors[*].data
规则:
  • JSON Body 仍然写成字符串,不要写成对象。
  • 多行内容用
    \n
    写入。
  • 预格式化只影响客户端展示可读性,不改变执行语义。
  • 处理器使用扁平结构
    { id, type, data, defaultEnable, enable }
    ,不要写旧式嵌套
    { type, config }
  • 处理器建议带稳定
    id
    ,尤其是
    assertion
    extractor
    customScript
    ;缺少
    id
    可能 validate 通过但运行器或客户端解析异常。
  • 提取全局变量时,
    data.variableType
    使用
    globals
    ;如需指定生效范围,
    data.shareScope
    优先使用
    PROJECT
    TEAM
    是团队范围,可能依赖增值能力,除非用户明确要求团队范围,否则不要默认使用。
  • 写入前照常跑
    cli-schema validate
  • 通过
    import-steps
    从 API definition 导入的步骤可能只有结构或 schema 示例值;运行前必须回读并按业务场景补齐 params、headers、body、脚本变量等。
示例:
json
{
  "requestBody": {
    "type": "application/json",
    "data": "{\n  \"name\": \"Demo\",\n  \"description\": \"Readable in client\"\n}"
  },
  "postProcessors": [
    {
      "id": "postProcessors.0.customScript",
      "type": "customScript",
      "data": "pm.test('返回 ID', function () {\n  var body = pm.response.json();\n  pm.expect(body.data.id).to.exist;\n});",
      "defaultEnable": true,
      "enable": true
    },
    {
      "id": "postProcessors.1.extractor",
      "type": "extractor",
      "data": {
        "variableName": "project_pet_name",
        "variableType": "globals",
        "shareScope": "PROJECT",
        "subject": "responseJson",
        "expression": "$.name"
      },
      "defaultEnable": true,
      "enable": true
    }
  ]
}
Apifox CLI will not automatically format scenario content; the client will display exactly what string is written. Pre-format string fields before writing:
  • Interface Body:
    requestBody.data
    .
  • Script Content:
    parameters.data
    .
  • Pre/Post Scripts:
    preProcessors[*].data
    ,
    postProcessors[*].data
    .
Rules:
  • JSON Body should still be written as a string, not an object.
  • Multi-line content is written with
    \n
    .
  • Pre-formatting only affects the readability of client display and does not change execution semantics.
  • Processors use a flat structure
    { id, type, data, defaultEnable, enable }
    instead of the old nested structure
    { type, config }
    .
  • It is recommended to add a stable
    id
    to processors, especially
    assertion
    ,
    extractor
    ,
    customScript
    ; missing
    id
    may pass validation but cause parsing exceptions in the runner or client.
  • When extracting global variables, use
    globals
    for
    data.variableType
    ; if you need to specify the scope, prioritize using
    PROJECT
    for
    data.shareScope
    .
    TEAM
    is a team-wide scope and may depend on value-added capabilities; do not use it by default unless the user explicitly requests team-wide scope.
  • Run
    cli-schema validate
    as usual before writing.
  • Steps imported from API definition via
    import-steps
    may only have structure or schema sample values; you must read back and supplement params, headers, body, script variables, etc. according to the business scenario before running.
Example:
json
{
  "requestBody": {
    "type": "application/json",
    "data": "{\n  \"name\": \"Demo\",\n  \"description\": \"Readable in client\"\n}"
  },
  "postProcessors": [
    {
      "id": "postProcessors.0.customScript",
      "type": "customScript",
      "data": "pm.test('Return ID', function () {\n  var body = pm.response.json();\n  pm.expect(body.data.id).to.exist;\n});",
      "defaultEnable": true,
      "enable": true
    },
    {
      "id": "postProcessors.1.extractor",
      "type": "extractor",
      "data": {
        "variableName": "project_pet_name",
        "variableType": "globals",
        "shareScope": "PROJECT",
        "subject": "responseJson",
        "expression": "$.name"
      },
      "defaultEnable": true,
      "enable": true
    }
  ]
}

断言和脚本规则

Assertion and Script Rules

常规校验优先用可视化
assertion
,自定义脚本只作为兜底能力。
断言规则:
  • 引用接口形成 HTTP 步骤时,优先使用原接口自带的契约测试/响应校验;默认契约通常已覆盖成功状态码,例如 200。
  • 已启用接口契约测试时,不要重复添加“HTTP 状态码为 200”这类同义断言;只补充契约外的业务断言。
  • 只有没有合适契约校验,或需要验证额外业务字段时,才单独添加
    assertion
  • HTTP 状态码、JSON 字段存在/相等、文本包含等常规校验优先用可视化
    assertion
    ,不要默认写
    customScript
  • 可视化断言字段使用当前 schema 枚举:HTTP 状态码用
    httpCode
    ,不要用
    responseCode
    ;JSON 字段用
    responseJson
    ,不要用
    responseBody
    ;全文包含用
    responseText
    +
    include
    ;比较符用
    equal
    ,不要用
    equals
json
{
  "type": "assertion",
  "data": {
    "name": "返回 ID",
    "subject": "responseJson",
    "comparison": "exists",
    "path": "$.data.id",
    "value": ""
  },
  "defaultEnable": true,
  "enable": true
}
脚本规则:
  • 自定义脚本只用于可视化断言覆盖不了的逻辑,例如复杂数组筛选、条件判断、二次请求、XML 转换或 schema 校验。
  • Apifox 脚本运行时通过
    pm
    对象读写变量、访问响应和定义断言;脚本断言使用
    pm.test(...)
    包裹。
  • 不要在
    pm.test
    外裸调用
    pm.response.json()
    ,避免空响应或非 JSON 响应导致错误难定位。
  • 不要凭经验扩展运行上下文字段。
js
pm.environment.set("variable_key", "variable_value");
pm.variables.set("variable_key", "variable_value");

pm.test("Status code is 200", function () {
  pm.response.to.have.status(200);
});

pm.test("JSON value equals expected", function () {
  var jsonData = pm.response.json();
  pm.expect(jsonData.value).to.eql(100);
});
Prioritize using visual
assertion
for regular checks; custom scripts are only used as a fallback capability.
Assertion Rules:
  • When referencing an interface to form an HTTP step, prioritize using the contract test/response verification built into the original interface; the default contract usually covers success status codes, such as 200.
  • When interface contract testing is enabled, do not repeatedly add synonymous assertions such as "HTTP status code is 200"; only add business assertions beyond the contract.
  • Only add
    assertion
    when there is no suitable contract verification or additional business fields need to be verified.
  • Prioritize using visual
    assertion
    for regular checks such as HTTP status code, JSON field existence/equality, text inclusion, etc.; do not write
    customScript
    by default.
  • Visual assertion fields use current schema enumerations: Use
    httpCode
    for HTTP status codes instead of
    responseCode
    ; use
    responseJson
    for JSON fields instead of
    responseBody
    ; use
    responseText
    +
    include
    for full-text inclusion; use
    equal
    for comparison operators instead of
    equals
    .
json
{
  "type": "assertion",
  "data": {
    "name": "Return ID",
    "subject": "responseJson",
    "comparison": "exists",
    "path": "$.data.id",
    "value": ""
  },
  "defaultEnable": true,
  "enable": true
}
Script Rules:
  • Custom scripts are only used for logic that cannot be covered by visual assertions, such as complex array filtering, conditional judgment, secondary requests, XML conversion or schema verification.
  • Apifox script runtime uses the
    pm
    object to read/write variables, access responses and define assertions; script assertions are wrapped with
    pm.test(...)
    .
  • Do not call
    pm.response.json()
    outside
    pm.test
    to avoid difficult-to-locate errors caused by empty responses or non-JSON responses.
  • Do not extend runtime context fields based on experience.
js
pm.environment.set("variable_key", "variable_value");
pm.variables.set("variable_key", "variable_value");

pm.test("Status code is 200", function () {
  pm.response.to.have.status(200);
});

pm.test("JSON value equals expected", function () {
  var jsonData = pm.response.json();
  pm.expect(jsonData.value).to.eql(100);
});

前后置和清理规则

Pre/Post and Cleanup Rules

  • 前置操作适合鉴权、准备数据、生成随机值、初始化数据库状态。
  • 后置操作适合清理测试数据、撤销副作用、释放资源。
  • 有副作用的场景必须考虑清理步骤,避免污染环境。
  • 数据库、外部程序、写入型接口步骤属于高风险操作,执行前确认环境不是生产环境。
  • Pre-operations are suitable for authentication, data preparation, random value generation, database state initialization.
  • Post-operations are suitable for cleaning up test data, undoing side effects, releasing resources.
  • Scenarios with side effects must consider cleanup steps to avoid polluting the environment.
  • High-risk operations such as database, external program, write-type interface steps require confirming that the environment is not a production environment before execution.

常见复杂步骤处理

Handling Common Complex Steps

步骤类型建模建议
接口请求步骤先确认 endpoint/case 或直接请求结构,输出关键响应字段
条件分支条件表达式必须基于已存在变量或响应字段
循环/迭代明确最大次数、退出条件和失败策略
等待/轮询明确等待上限,避免无限等待
脚本步骤输入输出变量要显式,避免隐式全局副作用
数据库步骤先确认连接、SQL 只操作测试数据,敏感信息不输出
清理步骤即使主流程失败,也尽量能执行清理
Step TypeModeling Suggestions
Interface Request StepFirst confirm the endpoint/case or direct request structure, output key response fields
Conditional BranchConditional expressions must be based on existing variables or response fields
Loop/IterationClarify the maximum number of times, exit conditions and failure strategies
Wait/PollClarify the wait upper limit to avoid infinite waiting
Script StepInput and output variables should be explicit to avoid implicit global side effects
Database StepFirst confirm the connection, SQL only operates test data, and sensitive information is not output
Cleanup StepTry to execute cleanup even if the main process fails

字段风险提醒

Field Risk Reminders

  • 步骤顺序看
    number
    ,不要只看回读数组顺序。
  • HTTP 步骤必须带正确接口绑定信息,避免变成孤立请求或客户端展示异常。可用
    type: "http"
    +
    bindId: <endpointId>
    +
    bindType: "API"
    +
    syncMode: "SYNC_WITH_API"
    +
    httpApiCase.apiDetailId
    导入接口;后端会生成
    relatedId
  • 常见 endpoint/test-case/test-scenario 导入不要手写上述复杂绑定结构,优先用
    test-scenario import-steps
    ;引用其它场景优先用
    test-scenario add-ref
  • 复杂业务场景通常需要
    syncMode: "MANUAL"
    承载定制参数、变量引用和断言,仅绑定 API 不等于可用业务场景。
  • 容器步骤
    group/if/else/loop/forEach/onError
    必须包含
    disable=false
    parameters
    isOpen=true
    children=[]
  • 子步骤放在
    children
    ,不要平铺。
  • group
    展示名写在
    parameters.name
    ,不是顶层
    name
  • if
    和条件
    break
    使用
    parameters.keyVariable
    +
    operator
    +
    valueVariable
    ,不要写
    expression
  • else
    onError
    parameters
    应为空对象
    {}
  • loop
    使用
    parameters.count
    ,不是
    times
    或其他字段。
  • delay
    使用
    parameters.timeout
    ,单位毫秒,不是
    duration
  • script
    步骤使用
    parameters.type="customScript"
    parameters.data=<JS code>
    enable=true
    ,不要写
    language/code
  • customHttp
    的 URL 字段叫
    customHttpRequest.path
    ,不是
    url
    ,且需要完整请求字段。
  • testCaseRef
    字段是
    relatedId
    ,不是
    caseId
  • relatedId
    是后端为场景步骤生成的 HTTP case ID,新建步骤时不要从旧场景复制复用。
  • test-scenario get --with-case-detail
    用于确认步骤树和 HTTP case/detail 内部配置,例如 Body、Header、postProcessors;如果用户明确要求验证可运行性,再执行运行验证并检查报告。
  • onError
    目前存在 CLI/schema/get 成功但客户端展开和配置展示不稳定的风险;涉及 onError 时不能仅凭 validate/get 成功判断可用,需要客户端确认。
  • Check the
    number
    for step order, do not only rely on the read-back array order.
  • HTTP steps must carry correct interface binding information to avoid becoming isolated requests or abnormal client display. You can import interfaces using
    type: "http"
    +
    bindId: <endpointId>
    +
    bindType: "API"
    +
    syncMode: "SYNC_WITH_API"
    +
    httpApiCase.apiDetailId
    ; the backend will generate
    relatedId
    .
  • Do not write the above complex binding structures manually for common endpoint/test-case/test-scenario imports; prioritize using
    test-scenario import-steps
    ; prioritize using
    test-scenario add-ref
    for referencing other scenarios.
  • Complex business scenarios usually require
    syncMode: "MANUAL"
    to carry customized parameters, variable references and assertions; only binding APIs does not mean it is a usable business scenario.
  • Container steps
    group/if/else/loop/forEach/onError
    must include
    disable=false
    ,
    parameters
    ,
    isOpen=true
    ,
    children=[]
    .
  • Sub-steps are placed in
    children
    , not flattened.
  • The display name of
    group
    is written in
    parameters.name
    , not the top-level
    name
    .
  • if
    and conditional
    break
    use
    parameters.keyVariable
    +
    operator
    +
    valueVariable
    , do not write
    expression
    .
  • parameters
    for
    else
    and
    onError
    should be empty objects
    {}
    .
  • loop
    uses
    parameters.count
    , not
    times
    or other fields.
  • delay
    uses
    parameters.timeout
    in milliseconds, not
    duration
    .
  • script
    steps use
    parameters.type="customScript"
    ,
    parameters.data=<JS code>
    ,
    enable=true
    , do not write
    language/code
    .
  • The URL field of
    customHttp
    is
    customHttpRequest.path
    , not
    url
    , and requires complete request fields.
  • The
    testCaseRef
    field is
    relatedId
    , not
    caseId
    .
  • relatedId
    is the HTTP case ID generated by the backend for scenario steps; do not copy and reuse it from old scenarios when creating new steps.
  • test-scenario get --with-case-detail
    is used to confirm the step tree and internal configurations of HTTP case/detail, such as Body, Header, postProcessors; if the user explicitly requests verifiability, then perform operation verification and check the report.
  • Currently,
    onError
    has the risk of unstable client expansion and configuration display even if CLI/schema/get is successful; when involving onError, you cannot judge availability solely based on successful validation/get, and need to confirm via the client.

验证和调试规则

Verification and Debugging Rules

  • cli-schema validate
    只保证基础 JSON 结构,不保证 runner、客户端或处理器一定能正确解析。
  • 更新或导入后先
    test-scenario get --with-case-detail
    确认步骤树非空且结构正确,但不要把 get 成功当成可运行。
  • 创建、更新或导入步骤后默认先回读确认,不要自动运行;只有用户明确要求运行、调试失败或交付前需要验证可运行性时,才执行
    test-scenario run
    并检查报告。
  • 运行失败时看报告步骤详情,区分失败发生在请求、前置脚本、后置脚本、断言、变量引用还是环境。
  • 调试复杂场景时不要反复覆盖同一个业务场景;必要时新建版本化场景,避免旧步骤和新结构混杂。
  • 临时删除脚本/断言可以用于定位问题,但不能把“删除功能”当成最终修复。
  • cli-schema validate
    only guarantees basic JSON structure, not that the runner, client or processor can definitely parse it correctly.
  • After update or import, first use
    test-scenario get --with-case-detail
    to confirm that the step tree is non-empty and the structure is correct, but do not treat successful get as runnable.
  • After creating, updating or importing steps, read back and confirm by default; do not run automatically; only execute
    test-scenario run
    and check the report when the user explicitly requests running, debugging failures or needs to verify runnability before delivery.
  • When running fails, check the step details in the report to distinguish whether the failure occurs in the request, pre-script, post-script, assertion, variable reference or environment.
  • Do not repeatedly overwrite the same business scenario when debugging complex scenarios; if necessary, create a versioned scenario to avoid mixing old steps and new structures.
  • Temporarily deleting scripts/assertions can be used to locate problems, but do not treat "deleting functions" as the final fix.

不可违反规则

Non-Violable Rules

  1. 不要把
    test-case
    的结构直接当作
    test-scenario
    步骤结构;导入单接口用例到场景优先使用
    test-scenario import-steps --source test-case --endpoint <endpointId> --ids <caseIds>
  2. 不要只创建一个空场景名;必须包含可展示、可运行的步骤结构。
  3. 不要误以为 create 能保存 steps;必须 create 元数据后再用
    import-steps
    add-ref
    update --file
    写入 steps。
  4. 不要凭经验猜复杂步骤字段;先读 schema 和现有场景模板。
  5. 不要让后续步骤引用未确认来源的数据;先确认它来自步骤响应、环境变量、迭代数据、extractor 或脚本输出。
  6. 不要在不确认环境的情况下执行有副作用步骤。
  7. 更新场景前必须先
    get --with-case-detail
    原结构,避免覆盖整个步骤树。
  8. 不要反复覆盖同一个复杂业务场景做调试;必要时新建版本化场景,避免旧步骤和新结构混杂。
  1. Do not directly use the structure of
    test-case
    as the step structure of
    test-scenario
    ; prioritize using
    test-scenario import-steps --source test-case --endpoint <endpointId> --ids <caseIds>
    to import single-interface test cases into scenarios.
  2. Do not only create an empty scenario name; it must contain a displayable and runnable step structure.
  3. Do not mistakenly think that create can save steps; you must create metadata first, then use
    import-steps
    ,
    add-ref
    or
    update --file
    to write steps.
  4. Do not guess complex step fields based on experience; read the schema and existing scenario templates first.
  5. Do not let subsequent steps reference data from unconfirmed sources; first confirm that it comes from step responses, environment variables, iterative data, extractor or script output.
  6. Do not execute steps with side effects without confirming the environment.
  7. Before updating a scenario, you must first
    get --with-case-detail
    the original structure to avoid overwriting the entire step tree.
  8. Do not repeatedly overwrite the same complex business scenario for debugging; if necessary, create a versioned scenario to avoid mixing old steps and new structures.

调试流程

Debugging Process

现象处理
场景创建成功但前端步骤不展示
test-scenario get
看真实保存结构,必要时转
apifox-cli-checkup
后续步骤变量为空检查上游 extractor、响应路径、变量名和执行顺序
场景 run 失败但单接口成功检查步骤间变量传递、环境、前置脚本和依赖顺序
循环或等待卡住检查退出条件、最大次数、timeout
清理没执行检查失败策略和后置步骤配置
报告没有步骤详情先按
apifox-test-automation
区分本地/云端报告,再必要时转
apifox-cli-checkup
PhenomenonHandling
Scenario created successfully but steps not displayed on the front endUse
test-scenario get
to check the real saved structure, switch to
apifox-cli-checkup
if necessary
Variables in subsequent steps are emptyCheck upstream extractor, response path, variable name and execution order
Scenario run fails but single interface succeedsCheck inter-step variable transfer, environment, pre-script and dependency order
Loop or wait gets stuckCheck exit conditions, maximum number of times, timeout
Cleanup not executedCheck failure strategy and post-step configuration
No step details in reportFirst distinguish between local/cloud reports according to
apifox-test-automation
, then switch to
apifox-cli-checkup
if necessary