sf-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesesf-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
核心职责
- Test Execution: Run Apex tests via with coverage analysis
sf apex run test - Coverage Analysis: Parse coverage reports, identify untested code paths
- Failure Analysis: Parse test failures, identify root causes, suggest fixes
- Agentic Test-Fix Loop: Automatically fix failing tests and re-run until passing
- Test Generation: Create test classes using sf-apex patterns
- Bulk Testing: Validate with 251+ records for governor limit safety
- 测试执行:通过运行Apex测试并进行覆盖率分析
sf apex run test - 覆盖率分析:解析覆盖率报告,识别未测试的代码路径
- 失败分析:解析测试失败结果,识别根本原因并提出修复建议
- 智能测试修复循环:自动修复失败的测试并重新运行,直至通过
- 测试生成:使用sf-apex模式创建测试类
- 批量测试:使用251+条记录验证以确保符合 governor 限制
Document Map
文档地图
| Need | Document | Description |
|---|---|---|
| Test patterns | references/test-patterns.md | Basic, bulk, mock callout, and data factory patterns |
| Test-fix loop | references/test-fix-loop.md | Agentic loop implementation & failure decision tree |
| Best practices | references/testing-best-practices.md | General testing guidelines |
| CLI commands | references/cli-commands.md | SF CLI test commands |
| Mocking | references/mocking-patterns.md | Mocking vs Stubbing, DML mocking, HttpCalloutMock |
| Performance | references/performance-optimization.md | Fast tests, reduce execution time |
| 需求 | 文档 | 描述 |
|---|---|---|
| 测试模式 | references/test-patterns.md | 基础、批量、模拟调用和数据工厂模式 |
| 测试修复循环 | references/test-fix-loop.md | 智能循环实现与失败分析决策树 |
| 最佳实践 | references/testing-best-practices.md | 通用测试指南 |
| CLI命令 | references/cli-commands.md | SF 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:
- Check existing tests: ,
Glob: **/*Test*.clsGlob: **/*_Test.cls - Check for Test Data Factories:
Glob: **/*TestDataFactory*.cls
询问用户以收集以下信息:
- 测试范围(单个类、所有测试、特定测试套件)
- 目标组织别名
- 覆盖率阈值要求(默认:75%,推荐:90%)
- 是否启用智能修复循环
随后:
- 检查现有测试:,
Glob: **/*Test*.clsGlob: **/*_Test.cls - 检查测试数据工厂:
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 and report:
test-results/test-run-id.json📊 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 testbash
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]:(v2.107.6+). For production, prefer separatesf logic run test --test-level RunLocalTests --code-coverage --target-org [alias]andsf apex run test.sf flow run test
针对Flow专属测试(非Apex),使用:
sf flow run testbash
sf flow run test --test-names FlowTest1,FlowTest2 --target-org [alias]
sf flow get test --test-run-id <id> --target-org [alias]统一测试运行器 [Beta]:(版本v2.107.6+)。生产环境中,建议优先使用单独的sf logic run test --test-level RunLocalTests --code-coverage --target-org [alias]和sf apex run test。sf flow run test
Phase 5: Coverage Improvement
阶段5:覆盖率提升
If coverage < threshold:
- to identify uncovered lines
sf apex run test --class-names MyClassTest --code-coverage --detailed-coverage --result-format json - Use sf-apex to generate test methods targeting those lines
- Use the sf-data skill: "Create 251 [ObjectName] records for bulk testing"
- Re-run and verify
如果覆盖率低于阈值:
- 执行以识别未覆盖的代码行
sf apex run test --class-names MyClassTest --code-coverage --detailed-coverage --result-format json - 使用sf-apex生成针对这些代码行的测试方法
- 使用sf-data技能:"创建251条[对象名称]记录用于批量测试"
- 重新运行并验证
Best Practices (120-Point Scoring)
最佳实践(120分评分体系)
| Category | Points | Key Rules |
|---|---|---|
| Test Coverage | 25 | 90%+ class coverage; all public methods tested; edge cases covered |
| Assertion Quality | 25 | Assert class used; meaningful messages; positive AND negative tests |
| Bulk Testing | 20 | Test with 251+ records; verify no SOQL/DML in loops under load |
| Test Data | 20 | Test Data Factory used; no hardcoded IDs; @TestSetup for efficiency |
| Isolation | 15 | SeeAllData=false; no org dependencies; mock external callouts |
| Documentation | 15 | Test 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提升效率 |
| 隔离性 | 15 | SeeAllData=false;无组织依赖;模拟外部调用 |
| 文档 | 15 | 测试方法名称描述场景;复杂设置添加注释 |
阈值:108+ 优秀 | 96+ 良好 | 84+ 合格 | 72+ 待改进 | <72 阻塞
Test Patterns & Templates
测试模式与模板
See references/test-patterns.md for full Apex code examples of all 4 patterns.
| Pattern | Template | Use Case |
|---|---|---|
| Basic Test Class | | Given-When-Then with @TestSetup, positive + negative |
| Bulk Test (251+) | | Cross 200-record batch boundary, governor limit check |
| Mock Callout | | HttpCalloutMock for external API testing |
| Test Data Factory | | Reusable data creation with convenience insert |
Additional templates: (35x faster tests), (dynamic behavior)
assets/dml-mock.clsassets/stub-provider-example.cls所有4种模式的完整Apex代码示例请参考 references/test-patterns.md。
| 模式 | 模板 | 使用场景 |
|---|---|---|
| 基础测试类 | | 采用@TestSetup的Given-When-Then模式,包含正向和反向测试 |
| 批量测试(251+条) | | 跨越200条记录的批处理边界,检查governor限制 |
| 模拟调用 | | 使用HttpCalloutMock进行外部API测试 |
| 测试数据工厂 | | 可复用的数据创建工具,支持便捷插入 |
额外模板:(测试速度提升35倍)、(动态行为)
assets/dml-mock.clsassets/stub-provider-example.clsTesting Guardrails (MANDATORY)
测试防护规则(强制要求)
BEFORE running tests, verify:
| Check | Command | Why |
|---|---|---|
| Org authenticated | | Tests need valid org connection |
| Classes deployed | | Can't test undeployed code |
| Test data exists | Check @TestSetup or TestDataFactory | Tests need data to operate on |
NEVER do these:
| Anti-Pattern | Problem | Correct Pattern |
|---|---|---|
| Tests depend on org data, break in clean orgs | Always |
| Hardcoded Record IDs | IDs differ between orgs | Query or create in test |
| No assertions | Tests pass without validating anything | Assert every expected outcome |
| Single record tests only | Misses bulk trigger issues | Always test with 200+ records |
| Async code won't execute | Always pair start/stop |
运行测试前,请验证:
| 检查项 | 命令 | 原因 |
|---|---|---|
| 组织已认证 | | 测试需要有效的组织连接 |
| 类已部署 | | 无法测试未部署的代码 |
| 测试数据存在 | 检查@TestSetup或TestDataFactory | 测试需要数据才能运行 |
绝对禁止以下操作:
| 反模式 | 问题 | 正确做法 |
|---|---|---|
| 测试依赖组织数据,在干净组织中会失效 | 始终使用 |
| 硬编码记录ID | 不同组织间ID不同 | 在测试中查询或创建记录 |
| 无断言 | 测试通过但未验证任何结果 | 对所有预期结果进行断言 |
| 仅单条记录测试 | 遗漏批量触发器问题 | 始终使用200+条记录测试 |
仅 | 异步代码不会执行 | 始终成对使用start/stop |
CLI Command Reference
CLI命令参考
| Command | Purpose | Example |
|---|---|---|
| Run tests | See Phase 2 examples |
| Get async test status | |
| List debug logs | |
| Stream logs real-time | |
Key flags: , , , , ,
--code-coverage--detailed-coverage--result-format json--output-dir--test-level RunLocalTests--concise| 命令 | 用途 | 示例 |
|---|---|---|
| 运行测试 | 见阶段2示例 |
| 获取异步测试状态 | |
| 列出调试日志 | |
| 实时流式查看日志 | |
关键参数:, , , , ,
--code-coverage--detailed-coverage--result-format json--output-dir--test-level RunLocalTests--conciseCommon Test Failures & Fixes
常见测试失败与修复方案
| Failure | Likely Cause | Fix |
|---|---|---|
| User + non-setup object in same txn | Use |
| Trigger or flow error | Check trigger logic with debug logs |
| Test data incomplete | Add required fields to TestDataFactory |
| Unique field conflict | Use dynamic values or delete existing |
| Validation rule fired | Meet validation criteria in test data |
| Record lock conflict | Use |
| 失败类型 | 可能原因 | 修复方案 |
|---|---|---|
| 同一事务中同时操作用户和非设置对象 | 使用 |
| 触发器或Flow错误 | 使用调试日志检查触发器逻辑 |
| 测试数据不完整 | 为测试数据工厂添加必填字段 |
| 唯一字段冲突 | 使用动态值或删除现有记录 |
| 触发了验证规则 | 在测试数据中满足验证规则条件 |
| 记录锁定冲突 | 使用 |
Cross-Skill Integration
跨技能集成
| Skill | When to Use | Example |
|---|---|---|
| sf-apex | Generate test classes, fix failing code | Use the sf-apex skill: "Create test class for LeadService" |
| sf-data | Create bulk test data (251+ records) | Use the sf-data skill: "Create 251 Leads for bulk testing" |
| sf-deploy | Deploy test classes to org | Use the sf-deploy skill: "Deploy tests to sandbox" |
| sf-debug | Analyze failures with debug logs | Use 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 CLI authenticated
Recommended: sf-apex (auto-fix), sf-data (bulk test data), sf-debug (log analysis)
sf必需:已通过 CLI认证的目标组织
推荐:sf-apex(自动修复)、sf-data(批量测试数据)、sf-debug(日志分析)
sf