running-apex-tests

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

running-apex-tests: Salesforce Test Execution & Coverage Analysis

running-apex-tests: Salesforce测试执行与覆盖率分析

Use this skill when the user needs Apex test execution and failure analysis: running tests, checking coverage, interpreting failures, improving coverage, and managing a disciplined test-fix loop for Salesforce code.
当用户需要Apex测试执行与失败分析时使用本技能:包括运行测试、检查覆盖率、解读失败原因、提升覆盖率,以及为Salesforce代码管理规范化的测试修复循环。

When This Skill Owns the Task

本技能负责的任务场景

Use
running-apex-tests
when the work involves:
  • sf apex run test
    workflows
  • Apex unit-test failures
  • code coverage analysis
  • identifying uncovered lines and missing test scenarios
  • structured test-fix loops for Apex code
Delegate elsewhere when the user is:
  • writing or refactoring production Apex →
    generating-apex
    skill
  • testing Agentforce agents →
    testing-agentforce
    skill
  • testing LWC with Jest → generating-lwc-components

当工作涉及以下内容时,使用
running-apex-tests
  • sf apex run test
    工作流
  • Apex单元测试失败
  • 代码覆盖率分析
  • 识别未覆盖代码行和缺失的测试场景
  • Apex代码的结构化测试修复循环
当用户进行以下操作时,请转交至其他技能:
  • 编写或重构生产环境Apex代码 →
    generating-apex
    技能
  • 测试Agentforce代理 →
    testing-agentforce
    技能
  • 使用Jest测试LWC → generating-lwc-components

Required Context to Gather First

首先需要收集的必要上下文

Ask for or infer:
  • target org alias
  • desired test scope: single class, specific methods, suite, or local tests
  • coverage threshold expectation
  • whether the user wants diagnosis only or a test-fix loop
  • whether related test data factories already exist

询问或推断:
  • 目标组织别名(org alias)
  • 期望的测试范围:单个类、特定方法、测试套件或本地测试
  • 覆盖率阈值要求
  • 用户仅需诊断还是需要完整的测试修复循环
  • 相关测试数据工厂是否已存在

Recommended Workflow

推荐工作流程

1. Discover test scope

1. 确定测试范围

Identify:
  • existing test classes
  • target production classes
  • test data factories / setup helpers
识别:
  • 现有测试类
  • 目标生产类
  • 测试数据工厂/设置辅助工具

2. Run the smallest useful test set first

2. 先运行最小有效测试集

Start narrow when debugging a failure; widen only after the fix is stable.
调试失败时从窄范围开始;仅在修复稳定后再扩大范围。

3. Analyze results

3. 分析结果

Focus on:
  • failing methods
  • exception types and stack traces
  • uncovered lines / weak coverage areas
  • whether failures indicate bad test data, brittle assertions, or broken production logic
重点关注:
  • 失败的方法
  • 异常类型和堆栈跟踪
  • 未覆盖代码行/覆盖率薄弱区域
  • 失败是否由测试数据不佳、断言脆弱或生产逻辑损坏导致

4. Run a disciplined fix loop

4. 执行规范化的修复循环

When the issue is code or test quality:
  • delegate code fixes to
    generating-apex
    skill when needed
  • add or improve tests
  • rerun focused tests before broader regression
当问题涉及代码或测试质量时:
  • 必要时将代码修复任务转交至
    generating-apex
    技能
  • 添加或改进测试
  • 在进行更广泛的回归测试前,重新运行聚焦测试

5. Improve coverage intentionally

5. 有针对性地提升覆盖率

Cover:
  • positive path
  • negative / exception path
  • bulk path (251+ records where appropriate)
  • callout or async path when relevant

覆盖以下场景:
  • 正向路径
  • 异常/错误路径
  • 批量路径(适当时使用251条以上记录)
  • 相关的调用或异步路径

High-Signal Rules

高价值规则

RuleRationale
Default to
SeeAllData=false
Ensures test isolation; prevents reliance on org-specific data
Every test must assert meaningful outcomesTests with no assertions prove nothing and give false confidence
Test bulk behavior with 251+ recordsTriggers process in batches of 200; 251 records crosses the boundary
Use factories /
@TestSetup
when they improve clarity
Consistent data creation in one place; rolled back between test methods
Pair
Test.startTest()
with
Test.stopTest()
for async
Ensures async operations (queueable, future) complete before assertions
Do not hide flaky org dependencies inside testsPrevents intermittent failures tied to org state

规则理由
默认使用
SeeAllData=false
确保测试隔离;避免依赖组织特定数据
每个测试必须断言有意义的结果无断言的测试无法证明任何内容,会带来虚假的信心
使用251条以上的测试数据验证批量行为触发器会按200条记录分批处理;251条记录会触发跨批次边界的逻辑
当工厂/
@TestSetup
能提升清晰度时使用它们
在一处创建一致的测试数据;测试方法间会自动回滚
异步操作需搭配
Test.startTest()
Test.stopTest()
确保异步操作(可排队、未来方法)在断言前完成
不要在测试中隐藏不稳定的组织依赖避免与组织状态相关的间歇性失败

Gotchas

常见问题与解决方法

IssueResolution
Test passes locally but fails in CI orgCheck for
SeeAllData=true
or undeclared dependencies on org-specific records
Coverage drops unexpectedly after refactorRun focused class-level tests first, then widen to
RunLocalTests
to confirm
"Uncommitted work pending" error in callout testDML and HTTP callouts cannot be mixed in the same test context without
Test.startTest()
wrapping
Mock not taking effect in testEnsure
Test.setMock()
is called before the code that makes the callout
@TestSetup
data missing in test method
@TestSetup
data is committed per test method — re-query it; do not store in static variables

问题解决方案
测试在本地通过但在CI组织中失败检查是否使用了
SeeAllData=true
或存在未声明的组织特定记录依赖
重构后覆盖率意外下降先运行聚焦类级别的测试,再扩大到
RunLocalTests
确认
调用测试中出现"Uncommitted work pending"错误在同一测试上下文中不能混合DML和HTTP调用,需用
Test.startTest()
包裹
测试中Mock未生效确保
Test.setMock()
在发起调用的代码之前执行
测试方法中
@TestSetup
数据丢失
@TestSetup
数据会在每个测试方法中提交 —— 重新查询数据;不要存储在静态变量中

Output Format

输出格式

When finishing, report in this order:
  1. What tests were run
  2. Pass/fail summary
  3. Coverage result
  4. Root-cause findings
  5. Fix or next-run recommendation
Suggested shape:
text
Test run: <scope>
Org: <alias>
Result: <passed / partial / failed>
Coverage: <percent / key classes>
Issues: <highest-signal failures>
Next step: <fix class, add test, rerun scope, or widen regression>

完成任务后,按以下顺序报告:
  1. 运行的测试范围
  2. 通过/失败总结
  3. 覆盖率结果
  4. 根本原因分析
  5. 修复或下一步运行建议
建议格式:
text
测试范围: <scope>
组织: <alias>
结果: <通过 / 部分通过 / 失败>
覆盖率: <百分比 / 关键类>
问题: <最高优先级的失败项>
下一步: <修复类、添加测试、重新运行当前范围或扩大回归测试范围>

Cross-Skill Integration

跨技能集成

NeedDelegate toReason
Fix production code or author test classes
generating-apex
skill
Code generation and repair
Create bulk / edge-case test datahandling-sf-dataRealistic test datasets
Deploy updated tests to orgdeploying-metadataDeployment workflows
Inspect detailed runtime logsdebugging-apex-logsDeeper failure analysis

需求转交至原因
修复生产代码或编写测试类
generating-apex
技能
代码生成与修复
创建批量/边缘场景测试数据handling-sf-data生成真实的测试数据集
将更新后的测试部署到组织deploying-metadata部署工作流
查看详细运行日志debugging-apex-logs深入分析失败原因

Reference File Index

参考文件索引

FileWhen to read
references/cli-commands.md
All
sf apex run test
command flags, output formats, async execution, and coverage commands
references/test-patterns.md
Test class templates — basic, bulk (251+), mock callout, and data factory patterns
references/testing-best-practices.md
Core testing principles — AAA pattern, naming conventions, bulk, negative, and mock strategies
references/test-fix-loop.md
Agentic test-fix loop implementation and failure analysis decision tree
references/mocking-patterns.md
HttpCalloutMock, DML mocking, StubProvider, and selector mocking patterns
references/performance-optimization.md
Techniques to reduce test execution time — DML mocking, SOQL mocking, loop optimizations
assets/basic-test.cls
Template: standard test class with
@TestSetup
, positive / negative / bulk / edge-case methods
assets/bulk-test.cls
Template: bulk test with 251+ records that crosses the 200-record trigger batch boundary
assets/mock-callout-test.cls
Template: HTTP callout mock using
HttpCalloutMock
assets/test-data-factory.cls
Template: reusable
TestDataFactory
with create and insert helpers
assets/dml-mock.cls
Template:
IDML
interface +
DMLMock
implementation for database-free unit tests
assets/stub-provider-example.cls
Template:
StubProvider
-based dependency injection stub
hooks/scripts/parse-test-results.py
Post-tool hook — parses
sf apex run test
JSON output and formats failures for the auto-fix loop

文件阅读场景
references/cli-commands.md
所有
sf apex run test
命令参数、输出格式、异步执行及覆盖率命令
references/test-patterns.md
测试类模板 —— 基础、批量(251+)、Mock调用及数据工厂模式
references/testing-best-practices.md
核心测试原则 —— AAA模式、命名规范、批量测试、异常测试及Mock策略
references/test-fix-loop.md
智能化测试修复循环实现及失败分析决策树
references/mocking-patterns.md
HttpCalloutMock、DML Mocking、StubProvider及选择器Mocking模式
references/performance-optimization.md
缩短测试执行时间的技巧 —— DML Mocking、SOQL Mocking、循环优化
assets/basic-test.cls
模板:包含
@TestSetup
、正向/异常/批量/边缘场景方法的标准测试类
assets/bulk-test.cls
模板:包含251+条记录的批量测试,用于触发跨200条记录的触发器批次边界逻辑
assets/mock-callout-test.cls
模板:使用
HttpCalloutMock
实现的HTTP调用Mock测试
assets/test-data-factory.cls
模板:可复用的
TestDataFactory
,包含创建和插入辅助方法
assets/dml-mock.cls
模板:
IDML
接口 +
DMLMock
实现,用于无数据库依赖的单元测试
assets/stub-provider-example.cls
模板:基于
StubProvider
的依赖注入Stub
hooks/scripts/parse-test-results.py
工具后处理钩子 —— 解析
sf apex run test
的JSON输出,为自动修复循环格式化失败信息

Score Guide

评分指南

ScoreMeaning
108+strong production-grade test confidence
96–107good test suite with minor gaps
84–95acceptable but strengthen coverage / assertions
< 84below standard; revise before relying on it
分数含义
108+强生产级测试可信度
96–107良好的测试套件,存在微小漏洞
84–95可接受,但需强化覆盖率/断言
< 84未达标准;在依赖前需修订