sf-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

sf-testing: Salesforce Test Execution & Coverage Analysis

sf-testing: Salesforce测试执行与覆盖率分析

Expert testing engineer specializing in Apex test execution, code coverage analysis, mock frameworks, and agentic test-fix loops. Execute tests, analyze failures, and automatically fix issues.
专业测试工程师,专注于Apex测试执行、代码覆盖率分析、模拟框架以及智能测试修复循环。可执行测试、分析失败原因并自动修复问题。

Core Responsibilities

核心职责

  1. Test Execution: Run Apex tests via
    sf apex run test
    with coverage analysis
  2. Coverage Analysis: Parse coverage reports, identify untested code paths
  3. Failure Analysis: Parse test failures, identify root causes, suggest fixes
  4. Agentic Test-Fix Loop: Automatically fix failing tests and re-run until passing
  5. Test Generation: Create test classes using sf-apex patterns
  6. Bulk Testing: Validate with 251+ records for governor limit safety
  1. 测试执行:通过
    sf apex run test
    运行Apex测试并进行覆盖率分析
  2. 覆盖率分析:解析覆盖率报告,识别未测试的代码路径
  3. 失败分析:解析测试失败结果,识别根本原因并提出修复建议
  4. 智能测试修复循环:自动修复失败的测试并重新运行,直至通过
  5. 测试生成:使用sf-apex模式创建测试类
  6. 批量测试:使用251+条记录验证以确保符合 governor 限制

Document Map

文档地图

NeedDocumentDescription
Test patternsreferences/test-patterns.mdBasic, bulk, mock callout, and data factory patterns
Test-fix loopreferences/test-fix-loop.mdAgentic loop implementation & failure decision tree
Best practicesreferences/testing-best-practices.mdGeneral testing guidelines
CLI commandsreferences/cli-commands.mdSF CLI test commands
Mockingreferences/mocking-patterns.mdMocking vs Stubbing, DML mocking, HttpCalloutMock
Performancereferences/performance-optimization.mdFast tests, reduce execution time

需求文档描述
测试模式references/test-patterns.md基础、批量、模拟调用和数据工厂模式
测试修复循环references/test-fix-loop.md智能循环实现与失败分析决策树
最佳实践references/testing-best-practices.md通用测试指南
CLI命令references/cli-commands.mdSF CLI测试命令
模拟技术references/mocking-patterns.md模拟与存根对比、DML模拟、HttpCalloutMock
性能优化references/performance-optimization.md快速测试、减少执行时间

Workflow (5-Phase Pattern)

工作流程(5阶段模式)

Phase 1: Test Discovery

阶段1:测试发现

Ask the user to gather:
  • Test scope (single class, all tests, specific test suite)
  • Target org alias
  • Coverage threshold requirement (default: 75%, recommended: 90%)
  • Whether to enable agentic fix loop
Then:
  1. Check existing tests:
    Glob: **/*Test*.cls
    ,
    Glob: **/*_Test.cls
  2. Check for Test Data Factories:
    Glob: **/*TestDataFactory*.cls
询问用户以收集以下信息:
  • 测试范围(单个类、所有测试、特定测试套件)
  • 目标组织别名
  • 覆盖率阈值要求(默认:75%,推荐:90%)
  • 是否启用智能修复循环
随后
  1. 检查现有测试:
    Glob: **/*Test*.cls
    ,
    Glob: **/*_Test.cls
  2. 检查测试数据工厂:
    Glob: **/*TestDataFactory*.cls

Phase 2: Test Execution

阶段2:测试执行

Run Single Test Class:
bash
sf apex run test --class-names MyClassTest --code-coverage --result-format json --output-dir test-results --target-org [alias]
Run All Tests:
bash
sf apex run test --test-level RunLocalTests --code-coverage --result-format json --output-dir test-results --target-org [alias]
Run Specific Methods:
bash
sf apex run test --tests MyClassTest.testMethod1 --tests MyClassTest.testMethod2 --code-coverage --result-format json --target-org [alias]
Run Test Suite / All Tests (Concise):
bash
sf apex run test --suite-names MySuite --code-coverage --result-format json --target-org [alias]
sf apex run test --test-level RunLocalTests --code-coverage --result-format json --concise --target-org [alias]
运行单个测试类
bash
sf apex run test --class-names MyClassTest --code-coverage --result-format json --output-dir test-results --target-org [alias]
运行所有测试
bash
sf apex run test --test-level RunLocalTests --code-coverage --result-format json --output-dir test-results --target-org [alias]
运行特定方法
bash
sf apex run test --tests MyClassTest.testMethod1 --tests MyClassTest.testMethod2 --code-coverage --result-format json --target-org [alias]
运行测试套件 / 所有测试(简洁模式)
bash
sf apex run test --suite-names MySuite --code-coverage --result-format json --target-org [alias]
sf apex run test --test-level RunLocalTests --code-coverage --result-format json --concise --target-org [alias]

Phase 3: Results Analysis

阶段3:结果分析

Parse
test-results/test-run-id.json
and report:
📊 TEST EXECUTION RESULTS
════════════════════════════════════════════════════════════════

SUMMARY
───────────────────────────────────────────────────────────────
✅ Passed:    42    ❌ Failed:    3    📈 Coverage: 78.5%

FAILED TESTS
───────────────────────────────────────────────────────────────
❌ AccountServiceTest.testBulkInsert
   Line 45: System.AssertException: Assertion Failed

COVERAGE BY CLASS
───────────────────────────────────────────────────────────────
Class                   Lines  Covered  Uncovered   %
AccountService          150    142      8           94.7% ✅
OpportunityTrigger      45     28       17          62.2% ⚠️
ContactHelper           30     15       15          50.0% ❌
解析
test-results/test-run-id.json
并生成报告:
📊 测试执行结果
════════════════════════════════════════════════════════════════

摘要
───────────────────────────────────────────────────────────────
✅ 通过:    42    ❌ 失败:    3    📈 覆盖率: 78.5%

失败测试
───────────────────────────────────────────────────────────────
❌ AccountServiceTest.testBulkInsert
   第45行: System.AssertException: 断言失败

按类划分的覆盖率
───────────────────────────────────────────────────────────────
类名称                   总行数  已覆盖  未覆盖   覆盖率
AccountService          150    142      8           94.7% ✅
OpportunityTrigger      45     28       17          62.2% ⚠️
ContactHelper           30     15       15          50.0% ❌

Phase 4: Agentic Test-Fix Loop

阶段4:智能测试修复循环

See references/test-fix-loop.md for the full implementation flow and failure analysis decision tree.
When tests fail, the agentic loop: parses failures → reads source → identifies root cause → invokes sf-apex to fix → re-runs (max 3 attempts). Key error types: AssertException, NullPointerException, DmlException, LimitException, QueryException.
完整的实现流程和失败分析决策树请参考 references/test-fix-loop.md
当测试失败时,智能循环会:解析失败结果 → 读取源代码 → 识别根本原因 → 调用sf-apex进行修复 → 重新运行(最多3次尝试)。关键错误类型:AssertException、NullPointerException、DmlException、LimitException、QueryException。

Cross-Skill: Flow Testing

跨技能:Flow测试

For Flow-specific tests (not Apex), use
sf flow run test
:
bash
sf flow run test --test-names FlowTest1,FlowTest2 --target-org [alias]
sf flow get test --test-run-id <id> --target-org [alias]
Unified Test Runner [Beta]:
sf logic run test --test-level RunLocalTests --code-coverage --target-org [alias]
(v2.107.6+). For production, prefer separate
sf apex run test
and
sf flow run test
.
针对Flow专属测试(非Apex),使用
sf flow run test
bash
sf flow run test --test-names FlowTest1,FlowTest2 --target-org [alias]
sf flow get test --test-run-id <id> --target-org [alias]
统一测试运行器 [Beta]
sf logic run test --test-level RunLocalTests --code-coverage --target-org [alias]
(版本v2.107.6+)。生产环境中,建议优先使用单独的
sf apex run test
sf flow run test

Phase 5: Coverage Improvement

阶段5:覆盖率提升

If coverage < threshold:
  1. sf apex run test --class-names MyClassTest --code-coverage --detailed-coverage --result-format json
    to identify uncovered lines
  2. Use sf-apex to generate test methods targeting those lines
  3. Use the sf-data skill: "Create 251 [ObjectName] records for bulk testing"
  4. Re-run and verify

如果覆盖率低于阈值
  1. 执行
    sf apex run test --class-names MyClassTest --code-coverage --detailed-coverage --result-format json
    以识别未覆盖的代码行
  2. 使用sf-apex生成针对这些代码行的测试方法
  3. 使用sf-data技能:"创建251条[对象名称]记录用于批量测试"
  4. 重新运行并验证

Best Practices (120-Point Scoring)

最佳实践(120分评分体系)

CategoryPointsKey Rules
Test Coverage2590%+ class coverage; all public methods tested; edge cases covered
Assertion Quality25Assert class used; meaningful messages; positive AND negative tests
Bulk Testing20Test with 251+ records; verify no SOQL/DML in loops under load
Test Data20Test Data Factory used; no hardcoded IDs; @TestSetup for efficiency
Isolation15SeeAllData=false; no org dependencies; mock external callouts
Documentation15Test method names describe scenario; comments for complex setup
Thresholds: 108+ Excellent | 96+ Good | 84+ Acceptable | 72+ Below standard | <72 BLOCKED

类别分值关键规则
测试覆盖率25类覆盖率90%+;所有公共方法均已测试;覆盖边缘场景
断言质量25使用Assert类;有意义的断言消息;包含正向和反向测试
批量测试20使用251+条记录测试;验证高负载下SOQL/DML无循环问题
测试数据20使用测试数据工厂;无硬编码ID;使用@TestSetup提升效率
隔离性15SeeAllData=false;无组织依赖;模拟外部调用
文档15测试方法名称描述场景;复杂设置添加注释
阈值:108+ 优秀 | 96+ 良好 | 84+ 合格 | 72+ 待改进 | <72 阻塞

Test Patterns & Templates

测试模式与模板

See references/test-patterns.md for full Apex code examples of all 4 patterns.
PatternTemplateUse Case
Basic Test Class
assets/basic-test.cls
Given-When-Then with @TestSetup, positive + negative
Bulk Test (251+)
assets/bulk-test.cls
Cross 200-record batch boundary, governor limit check
Mock Callout
assets/mock-callout-test.cls
HttpCalloutMock for external API testing
Test Data Factory
assets/test-data-factory.cls
Reusable data creation with convenience insert
Additional templates:
assets/dml-mock.cls
(35x faster tests),
assets/stub-provider-example.cls
(dynamic behavior)

所有4种模式的完整Apex代码示例请参考 references/test-patterns.md
模式模板使用场景
基础测试类
assets/basic-test.cls
采用@TestSetup的Given-When-Then模式,包含正向和反向测试
批量测试(251+条)
assets/bulk-test.cls
跨越200条记录的批处理边界,检查governor限制
模拟调用
assets/mock-callout-test.cls
使用HttpCalloutMock进行外部API测试
测试数据工厂
assets/test-data-factory.cls
可复用的数据创建工具,支持便捷插入
额外模板:
assets/dml-mock.cls
(测试速度提升35倍)、
assets/stub-provider-example.cls
(动态行为)

Testing Guardrails (MANDATORY)

测试防护规则(强制要求)

BEFORE running tests, verify:
CheckCommandWhy
Org authenticated
sf org display --target-org [alias]
Tests need valid org connection
Classes deployed
sf project deploy report --target-org [alias]
Can't test undeployed code
Test data existsCheck @TestSetup or TestDataFactoryTests need data to operate on
NEVER do these:
Anti-PatternProblemCorrect Pattern
@IsTest(SeeAllData=true)
Tests depend on org data, break in clean orgsAlways
SeeAllData=false
(default)
Hardcoded Record IDsIDs differ between orgsQuery or create in test
No assertionsTests pass without validating anythingAssert every expected outcome
Single record tests onlyMisses bulk trigger issuesAlways test with 200+ records
Test.startTest()
without
Test.stopTest()
Async code won't executeAlways pair start/stop

运行测试前,请验证
检查项命令原因
组织已认证
sf org display --target-org [alias]
测试需要有效的组织连接
类已部署
sf project deploy report --target-org [alias]
无法测试未部署的代码
测试数据存在检查@TestSetup或TestDataFactory测试需要数据才能运行
绝对禁止以下操作
反模式问题正确做法
@IsTest(SeeAllData=true)
测试依赖组织数据,在干净组织中会失效始终使用
SeeAllData=false
(默认值)
硬编码记录ID不同组织间ID不同在测试中查询或创建记录
无断言测试通过但未验证任何结果对所有预期结果进行断言
仅单条记录测试遗漏批量触发器问题始终使用200+条记录测试
Test.startTest()
不使用
Test.stopTest()
异步代码不会执行始终成对使用start/stop

CLI Command Reference

CLI命令参考

CommandPurposeExample
sf apex run test
Run testsSee Phase 2 examples
sf apex get test
Get async test status
--test-run-id 707xx...
sf apex list log
List debug logs
--target-org alias
sf apex tail log
Stream logs real-time
--target-org alias
Key flags:
--code-coverage
,
--detailed-coverage
,
--result-format json
,
--output-dir
,
--test-level RunLocalTests
,
--concise

命令用途示例
sf apex run test
运行测试见阶段2示例
sf apex get test
获取异步测试状态
--test-run-id 707xx...
sf apex list log
列出调试日志
--target-org alias
sf apex tail log
实时流式查看日志
--target-org alias
关键参数
--code-coverage
,
--detailed-coverage
,
--result-format json
,
--output-dir
,
--test-level RunLocalTests
,
--concise

Common Test Failures & Fixes

常见测试失败与修复方案

FailureLikely CauseFix
MIXED_DML_OPERATION
User + non-setup object in same txnUse
System.runAs()
or separate transactions
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY
Trigger or flow errorCheck trigger logic with debug logs
REQUIRED_FIELD_MISSING
Test data incompleteAdd required fields to TestDataFactory
DUPLICATE_VALUE
Unique field conflictUse dynamic values or delete existing
FIELD_CUSTOM_VALIDATION_EXCEPTION
Validation rule firedMeet validation criteria in test data
UNABLE_TO_LOCK_ROW
Record lock conflictUse
FOR UPDATE
or retry logic

失败类型可能原因修复方案
MIXED_DML_OPERATION
同一事务中同时操作用户和非设置对象使用
System.runAs()
或拆分事务
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY
触发器或Flow错误使用调试日志检查触发器逻辑
REQUIRED_FIELD_MISSING
测试数据不完整为测试数据工厂添加必填字段
DUPLICATE_VALUE
唯一字段冲突使用动态值或删除现有记录
FIELD_CUSTOM_VALIDATION_EXCEPTION
触发了验证规则在测试数据中满足验证规则条件
UNABLE_TO_LOCK_ROW
记录锁定冲突使用
FOR UPDATE
或重试逻辑

Cross-Skill Integration

跨技能集成

SkillWhen to UseExample
sf-apexGenerate test classes, fix failing codeUse the sf-apex skill: "Create test class for LeadService"
sf-dataCreate bulk test data (251+ records)Use the sf-data skill: "Create 251 Leads for bulk testing"
sf-deployDeploy test classes to orgUse the sf-deploy skill: "Deploy tests to sandbox"
sf-debugAnalyze failures with debug logsUse the sf-debug skill: "Analyze test failure logs"

技能使用场景示例
sf-apex生成测试类、修复失败代码使用sf-apex技能:"为LeadService创建测试类"
sf-data创建批量测试数据(251+条记录)使用sf-data技能:"创建251条Lead记录用于批量测试"
sf-deploy将测试类部署到组织使用sf-deploy技能:"将测试部署到沙盒"
sf-debug使用调试日志分析失败原因使用sf-debug技能:"分析测试失败日志"

Dependencies

依赖项

Required: Target org with
sf
CLI authenticated Recommended: sf-apex (auto-fix), sf-data (bulk test data), sf-debug (log analysis)
必需:已通过
sf
CLI认证的目标组织 推荐:sf-apex(自动修复)、sf-data(批量测试数据)、sf-debug(日志分析)