platform-apex-test-run
forcedotcom/sf-skills
Run Apex tests, analyze coverage, and fix failures in Salesforce with structured test-fix loops.
What is platform-apex-test-run?
Execute Apex unit tests, measure code coverage, diagnose failures, and manage disciplined test-fix workflows in Salesforce orgs. Use this skill when running tests, checking coverage, fixing test failures, or working with *Test.cls files—not for writing production Apex code or LWC/Jest tests.
- Execute Apex tests via sf apex run test with configurable scope (single class, methods, suite, or local tests)
- Analyze code coverage results and identify uncovered lines and weak coverage areas
- Diagnose test failures with exception types, stack traces, and root-cause analysis
- Manage structured test-fix loops: run → analyze → fix → rerun
- Apply high-signal testing patterns: SeeAllData=false, bulk testing (251+ records), mock callouts, and @TestSetup data factories
How to install platform-apex-test-run
npx skills add https://github.com/forcedotcom/sf-skills --skill platform-apex-test-run- Salesforce CLI (sf) version 2.0.0 or higher
- Python 3.10.0 or higher (for test result parsing)
- jq 1.6.0 or higher (for JSON processing)
- Access to a Salesforce org with Apex test execution permissions
How to use platform-apex-test-run
- 1.Identify the test scope: single test class, specific methods, suite, or local tests, and confirm the target org alias
- 2.Run the smallest useful test set first using sf apex run test with appropriate flags (--class-names, --method-names, or --test-level)
- 3.Analyze the test results: review pass/fail summary, coverage percentage, failing methods, and exception stack traces
- 4.For failures, determine root cause: bad test data, brittle assertions, broken production logic, or missing mocks
- 5.Delegate code fixes to platform-apex-generate skill if needed; add or improve tests; rerun focused tests before broader regression
- 6.Improve coverage intentionally by adding tests for positive path, negative/exception path, bulk path (251+ records), and async/callout scenarios
Use cases
- Debug a failing Apex test class and identify whether the issue is bad test data, brittle assertions, or broken production logic
- Run a focused test suite on a single class, then widen to RunLocalTests for regression confirmation
- Improve code coverage by identifying uncovered lines and adding positive, negative, bulk, and async test scenarios
- Validate test isolation by ensuring tests use SeeAllData=false and do not depend on org-specific data
- Diagnose callout or async test failures by checking Test.startTest/stopTest wrapping and mock setup
- Salesforce developers writing and maintaining Apex unit tests
- QA engineers validating test coverage and test quality before deployment
- Platform engineers managing test-fix loops and coverage thresholds in CI/CD pipelines
platform-apex-test-run FAQ
Use platform-apex-test-run for running tests, analyzing coverage, diagnosing failures, and managing test-fix loops. Use platform-apex-generate when writing or refactoring production Apex code or authoring new test classes from scratch.
Salesforce triggers batch DML in groups of 200 records. Testing with 251+ records ensures your code handles the boundary condition where a second batch is created, catching bulk-processing bugs that smaller test datasets miss.
SeeAllData=false (the default) ensures tests use only data they create, preventing reliance on org-specific records. This makes tests portable and reliable across orgs; SeeAllData=true hides dependencies and causes intermittent CI failures.
DML and HTTP callouts cannot be mixed in the same test context. Wrap the callout code in Test.startTest() and Test.stopTest() to isolate the callout, or use HttpCalloutMock to avoid the actual HTTP call.
Check for SeeAllData=true, undeclared dependencies on org-specific records, or missing permission sets. Run the test in the CI org with verbose logging to confirm the actual failure; use System.runAs with a permission set if user-mode behavior is required.
Full instructions (SKILL.md)
Source of truth, from forcedotcom/sf-skills.
name: platform-apex-test-run description: "Apex test execution, coverage analysis, and test-fix loops with 120-point scoring. Use when the user runs Apex tests, checks code coverage, fixes failing tests, or touches *Test.cls / *_Test.cls files. DO NOT TRIGGER when writing Apex production code (use platform-apex-generate), Agentforce agent testing (use agentforce-test), or Jest/LWC tests (use experience-lwc-generate)." metadata: version: "1.2" domains: ["Platform"] relatedSkills: - "agentforce-test" - "experience-lwc-generate" - "platform-apex-generate" - "platform-apex-logs-debug" - "platform-data-manage" - "platform-metadata-deploy" cliTools: - tool: ["jq"] semver: ">=1.6.0" - tool: ["python3"] semver: ">=3.10.0" - tool: ["sf"] semver: ">=2.0.0"
platform-apex-test-run: Salesforce Test Execution & Coverage Analysis
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.
When This Skill Owns the Task
Use platform-apex-test-run when the work involves:
sf apex run testworkflows- 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 →
platform-apex-generateskill - testing Agentforce agents →
agentforce-testskill - testing LWC with Jest → experience-lwc-generate
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
Recommended Workflow
1. Discover test scope
Identify:
- existing test classes
- target production classes
- test data factories / setup helpers
2. Run the smallest useful test set first
Start narrow when debugging a failure; widen only after the fix is stable.
3. Analyze results
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
When the issue is code or test quality:
- delegate code fixes to
platform-apex-generateskill when needed - add or improve tests
- rerun focused tests before broader regression
5. Improve coverage intentionally
Cover:
- positive path
- negative / exception path
- bulk path (251+ records where appropriate)
- callout or async path when relevant
High-Signal Rules
| Rule | Rationale |
|---|---|
Default to SeeAllData=false | Ensures test isolation; prevents reliance on org-specific data |
| Every test must assert meaningful outcomes | Tests with no assertions prove nothing and give false confidence |
| Test bulk behavior with 251+ records | Triggers 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 tests | Prevents intermittent failures tied to org state |
Gotchas
| Issue | Resolution |
|---|---|
| Test passes locally but fails in CI org | Check for SeeAllData=true or undeclared dependencies on org-specific records |
| Coverage drops unexpectedly after refactor | Run focused class-level tests first, then widen to RunLocalTests to confirm |
| "Uncommitted work pending" error in callout test | DML and HTTP callouts cannot be mixed in the same test context without Test.startTest() wrapping |
| Mock not taking effect in test | Ensure 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 |
| API version 67.0 and higher without necessary access level checks | Check failing SOQL/DML stack traces for CRUD/FLS access errors, using System.runAs with an assigned permission set when user-mode behavior is intended, or documenting a justified SYSTEM_MODE path when system access is required |
Output Format
When finishing, report in this order:
- What tests were run
- Pass/fail summary
- Coverage result
- Root-cause findings
- Fix or next-run recommendation
Suggested shape:
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>
Cross-Skill Integration
| Need | Delegate to | Reason |
|---|---|---|
| Fix production code or author test classes | platform-apex-generate skill | Code generation and repair |
| Create bulk / edge-case test data | platform-data-manage | Realistic test datasets |
| Deploy updated tests to org | platform-metadata-deploy | Deployment workflows |
| Inspect detailed runtime logs | platform-apex-logs-debug | Deeper failure analysis |
Reference File Index
| File | When 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 |
scripts/parse-test-results.py | Post-tool hook — parses sf apex run test JSON output and formats failures for the auto-fix loop |
Score Guide
| Score | Meaning |
|---|---|
| 108+ | strong production-grade test confidence |
| 96–107 | good test suite with minor gaps |
| 84–95 | acceptable but strengthen coverage / assertions |
| < 84 | below standard; revise before relying on it |
Related skills
More from forcedotcom/sf-skills and the wider catalog.

platform-architecture-analyze
Holistic Well-Architected review of Salesforce DX projects: grades observable code/metadata criteria and emits governance checklist.

platform-capability-search
Discover Salesforce capabilities and plugins matched to your task or journey stage.

platform-custom-application-generate
Create and configure tab-based Salesforce Lightning Custom Applications with navigation, branding, and action overrides.

platform-custom-field-generate
Generate and validate Salesforce Custom Field metadata XML with built-in constraints for Roll-Up Summary and Master-Detail relationships.

platform-custom-lightning-type-generate
Generate Custom Lightning Types (CLTs) for Einstein Agent actions and structured schemas on Salesforce.

platform-custom-object-generate
Create and validate Salesforce Custom Object metadata with proper sharing models and field constraints.