Test Scenario Modeling
Prerequisites: Read
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
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
- Test cases under a single interface: Switch to .
- Only run existing scenarios, suites or CI commands: Switch to .
- Only view reports: Use according to current CLI help; refer to 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
| Concept | CLI Resource | Description |
|---|
| Interface Test Case | | Case bound to a specific endpoint, suitable for single-interface verification |
| Test Scenario | | Multi-step workflow orchestration, supports complex step connections |
| Test Suite | | Collection of scenarios/cases and regression organization |
| Environment | | Provides baseUrl, variables, service configurations |
| Test Data | | Iterative data source for scenarios or cases |
Command Entry
Use the current CLI help to query parameters for
.
and
may not appear in the top-level "Available Commands" list, but each supports
and can be used to import steps and add scenario references.
Key Fact:
only saves metadata. Even if
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
, and then add or modify steps using
,
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:
- copies/imports steps as part of the current scenario.
- adds a step that references another scenario without copying the internal steps of the source scenario.
- is the default mode, suitable for supplementing business parameters, variable references and assertions after import.
- 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
- Clarify business objectives: What process to verify, what are the success conditions, how to clean up in case of failure.
- Confirm project, branch, environment.
- List involved endpoints, cases, environment variables, test data, database connections or scripts.
- 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.
- If there are similar existing scenarios, first use to read them as templates.
- Design the step diagram in natural language first, then convert it to JSON; do not write while guessing fields.
- Obtain the schema to create metadata.
- After creation, use
test-scenario get --with-case-detail
to read back the complete structure.
- When importing existing resources, prioritize using or instead of writing complex binding fields directly.
- After import, use
test-scenario get --with-case-detail
again to confirm that steps are written and HTTP case/detail are expanded normally.
- 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.
- When performing fine-grained editing, obtain the schema and add or modify steps based on the complete structure.
- After passing , perform the update, then use
test-scenario get --with-case-detail
to confirm that are non-empty and the structure is correct.
The
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
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
- 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 .
- 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 still points to the correct step.
- Do not assume that the response path must be ; confirm the path based on the real response first, such as ,
{{$.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, and only apply to ; do not write them into single-interface .
List responses can be used as
, 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:
. 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 will not automatically format scenario content; the client will display exactly what string is written. Pre-format string fields before writing:
- Interface Body: .
- Script Content: .
- Pre/Post Scripts: , .
Rules:
- JSON Body should still be written as a string, not an object.
- Multi-line content is written with .
- 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 .
- It is recommended to add a stable to processors, especially , , ; missing may pass validation but cause parsing exceptions in the runner or client.
- When extracting global variables, use for ; if you need to specify the scope, prioritize using for . 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 as usual before writing.
- Steps imported from API definition via 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
Prioritize using visual
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 when there is no suitable contract verification or additional business fields need to be verified.
- Prioritize using visual for regular checks such as HTTP status code, JSON field existence/equality, text inclusion, etc.; do not write by default.
- Visual assertion fields use current schema enumerations: Use for HTTP status codes instead of ; use for JSON fields instead of ; use + for full-text inclusion; use for comparison operators instead of .
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 object to read/write variables, access responses and define assertions; script assertions are wrapped with .
- Do not call outside 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
| Step Type | Modeling Suggestions |
|---|
| Interface Request Step | First confirm the endpoint/case or direct request structure, output key response fields |
| Conditional Branch | Conditional expressions must be based on existing variables or response fields |
| Loop/Iteration | Clarify the maximum number of times, exit conditions and failure strategies |
| Wait/Poll | Clarify the wait upper limit to avoid infinite waiting |
| Script Step | Input and output variables should be explicit to avoid implicit global side effects |
| Database Step | First confirm the connection, SQL only operates test data, and sensitive information is not output |
| Cleanup Step | Try to execute cleanup even if the main process fails |
Field Risk Reminders
- Check the 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 + + +
syncMode: "SYNC_WITH_API"
+ ; the backend will generate .
- 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 for referencing other scenarios.
- Complex business scenarios usually require 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 , , , .
- Sub-steps are placed in , not flattened.
- The display name of is written in , not the top-level .
- and conditional use + + , do not write .
- for and should be empty objects .
- uses , not or other fields.
- uses in milliseconds, not .
- steps use
parameters.type="customScript"
, parameters.data=<JS code>
, , do not write .
- The URL field of is , not , and requires complete request fields.
- The field is , not .
- 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, 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
- 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 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
- Do not directly use the structure of as the step structure of ; prioritize using
test-scenario import-steps --source test-case --endpoint <endpointId> --ids <caseIds>
to import single-interface test cases into scenarios.
- Do not only create an empty scenario name; it must contain a displayable and runnable step structure.
- Do not mistakenly think that create can save steps; you must create metadata first, then use , or to write steps.
- Do not guess complex step fields based on experience; read the schema and existing scenario templates first.
- 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.
- Do not execute steps with side effects without confirming the environment.
- Before updating a scenario, you must first the original structure to avoid overwriting the entire step tree.
- 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
| Phenomenon | Handling |
|---|
| Scenario created successfully but steps not displayed on the front end | Use to check the real saved structure, switch to if necessary |
| Variables in subsequent steps are empty | Check upstream extractor, response path, variable name and execution order |
| Scenario run fails but single interface succeeds | Check inter-step variable transfer, environment, pre-script and dependency order |
| Loop or wait gets stuck | Check exit conditions, maximum number of times, timeout |
| Cleanup not executed | Check failure strategy and post-step configuration |
| No step details in report | First distinguish between local/cloud reports according to , then switch to if necessary |