/salesforce-development:platform-apex-test-generatefrom Salesforce Development
Generates and validates Apex test classes using TestDataFactory patterns, bulk testing with 251+ records, mocking, and Assert class. Triggers on *Test.cls files and sf apex run test.
Ships in Salesforce Development. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Generate production-ready Apex test classes and run disciplined test-fix loops with coverage analysis.
_NullInput_ and _EmptyInput_ as separate test methodsexecute() invocation runs, so set batchSize >= testRecordCount. See references/async-testing.md@TestSetup must delegate record creation to a TestDataFactory class. If none exists, create one first. Never build record lists inline in @TestSetup. Never rely on org data (SeeAllData=false) or hardcoded IDs. For duplicate rule handling, see references/test-data-factory.mdAssert class only — Assert.areEqual, Assert.isTrue, Assert.fail, etc. Never use legacy System.assert, System.assertEquals, or System.assertNotEquals
Assert methods exist: areEqual, areNotEqual, isTrue, isFalse, isNull, isNotNull, fail, isInstanceOfType, isNotInstanceOfType. There is no areSame / areNotSame -- to check identity or equality of SObjects, compare Id or specific fields with Assert.areEqualtrigger is a reserved word in Apex -- never use it as a variable name (e.g., use cronTrigger for a CronTrigger record; query CronTrigger fields CronExpression, State, TimesTriggered, NextFireTime, and CronJobDetail.Name from that variable)HttpCalloutMock for callouts, Test.setFixedSearchResults for SOSL, DML mock classes for database isolation. Design for testability via constructor injection. See references/mocking-patterns.mdTest.startTest() with Test.stopTest() to reset governor limits and force async executionAlways wrap the code under test in Test.startTest() / Test.stopTest():
| Anti-Pattern | Fix |
|---|---|
| SOQL/DML inside loops | Query once before the loop; use Map<Id, SObject> for lookups |
| Magic numbers in assertions | Derive expected values from setup constants |
| God test class (>500 lines) | Split into multiple test classes by behavior area |
| Long test methods (>30 lines) | Extract Given/When/Then into helper methods |
Generic Exception catch | Catch the specific expected type (e.g., DmlException) |
Before generating or fixing tests, identify:
integration-apex-symbol-table-query skill to get their exact method signatures, fields, and inner types rather than inferring them. If the org does not support it (API v67.0+ required) or the call fails, read the source insteadApply the structure, naming conventions, and patterns from the asset templates and reference docs.
MANDATORY — File Deliverables: For every test class, create BOTH files:
{ClassName}Test.cls — the test class (use assets/test-class-template.cls as starting point){ClassName}Test.cls-meta.xml — the metadata file:<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<status>Active</status>
</ApexClass>
If no TestDataFactory exists in the project, create TestDataFactory.cls + TestDataFactory.cls-meta.xml using assets/test-data-factory-template.cls.
@TestSetup
static void setupTestData() {
List<Account> accounts = TestDataFactory.createAccounts(251, true);
}
Use Given/When/Then:
@isTest
static void shouldUpdateStatus_WhenValidInput() {
// Given
List<Account> accounts = [SELECT Id FROM Account];
// When
Test.startTest();
MyService.processAccounts(accounts);
Test.stopTest();
// Then
List<Account> updated = [SELECT Id, Status__c FROM Account];
Assert.areEqual(251, updated.size(), 'All accounts should be processed');
}
Use try/catch with Assert.fail to verify expected exceptions:
@isTest
static void shouldThrowException_WhenInvalidInput() {
// Given
List<Account> emptyList = new List<Account>();
// When/Then
Test.startTest();
try {
MyService.processAccounts(emptyList);
Assert.fail('Expected MyCustomException to be thrown');
} catch (MyCustomException e) {
Assert.isTrue(e.getMessage().contains('cannot be empty'),
'Exception message should indicate empty input');
}
Test.stopTest();
}
should[ExpectedResult]_When[Scenario]: shouldSendNotification_WhenOpportunityClosedWon[SubjectOrAction]_[Scenario]_[ExpectedResult]: AccountUpdate_ChangeName_SuccessStart narrow when debugging; widen after the fix is stable.
# Single test class
sf apex run test --class-names MyServiceTest --result-format human --code-coverage --target-org <alias>
# Specific test methods
sf apex run test --tests MyServiceTest.shouldUpdateStatus_WhenValidInput --result-format human --target-org <alias>
# All local tests
sf apex run test --test-level RunLocalTests --result-format human --code-coverage --target-org <alias>
Focus on:
When tests fail, run a disciplined fix loop (max 3 iterations — stop and surface root cause if still failing):
platform-apex-generate skill| Level | Coverage | Purpose |
|---|---|---|
| Production deploy | 75% minimum | Required by Salesforce |
| Recommended | 90%+ | Best practice target |
| Critical paths | 100% | Business-critical code |
Cover all paths: positive, negative/exception, bulk (251+ records), callout/async.
| Component | Key Test Scenarios |
|---|---|
| Trigger | Bulk insert/update/delete, recursion guard, field change detection |
| Service | Valid/invalid inputs, bulk operations, exception handling |
| Controller | Page load, action methods, view state |
| Batch | start/execute/finish, scope matching (batch size >= record count), Database.Stateful tracking, error handling, chaining (separate methods — finish() calling Database.executeBatch() throws UnexpectedException) |
| Queueable | Chaining (only first job runs in tests), bulkification, error handling, callout mocks before Test.startTest() |
| Callout | Success response, error response, timeout |
| Selector | Valid/null/empty inputs, bulk (251+), field population, sort order, WITH USER_MODE via System.runAs |
| Scheduled | Direct execution via execute(null), CRON registration via CronTrigger query |
| Platform Event | Test.enableChangeDataCapture(), Test.getEventBus().deliver(), verify subscriber side effects |
Deliverables per test class:
{ClassName}Test.cls + {ClassName}Test.cls-meta.xml (match API version of class under test; default 66.0)TestDataFactory.cls + TestDataFactory.cls-meta.xml (if not already present)Load on demand for detailed patterns:
| Reference | When to use |
|---|---|
| references/test-data-factory.md | TestDataFactory patterns, field overrides, duplicate rule handling |
| references/assertion-patterns.md | Assertion best practices, anti-patterns, common pitfalls |
| references/mocking-patterns.md | HttpCalloutMock, DML mocking, StubProvider, SOSL, Email, Platform Events |
| references/async-testing.md | Batch, Queueable, Future, Scheduled job testing |
assets/test-class-template.cls (opens in a new tab)assets/test-data-factory-template.cls (opens in a new tab)references/assertion-patterns.md (opens in a new tab)references/async-testing.md (opens in a new tab)references/mocking-patterns.md (opens in a new tab)references/test-data-factory.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
38 skills in this plugin
/automation-flow-generateGenerate Salesforce Flows using the MCP tool execute_metadata_action. Use when the user asks to create, build, or generate a flow — including Screen, Autolaunched, Record-Triggered (before/after-save), Scheduled. Also trigger for flow-like requests such as "when a record is created", "trigger daily at", "send an email when", "update the field when", "automate", "workflow", or "flow XML/metadata". This is the only skill for Salesforce Flow generation./dx-org-manageUse to EXECUTE Salesforce org operations immediately via the sf CLI (this skill runs them, it does NOT generate scripts): create scratch orgs (from edition, definition file, snapshot, or org shape), list/display/resume/delete scratch orgs, open orgs in browser. Trigger: 'create scratch org', 'create org from snapshot', 'delete scratch org', 'open my org'. Do NOT use for switching the default org (use dx-org-switch), deploying metadata (use platform-metadata-deploy), or creating/checking/listing/deleting org snapshots (use dx-org-snapshot-manage)./dx-project-createScaffold a Salesforce DX project from any template (standard, agent, analytics, React/Angular/Vue app), move the session in, connect an org, enable source tracking. Use to create a Salesforce/SFDX project. DO NOT TRIGGER for: existing UI-bundle apps (experience-ui-bundle-frontend-generate); UI-bundle scaffold in a larger build (experience-ui-bundle-project-generate, experience-ui-bundle-app-coordinate); tool checks (platform-environment-validate); org login (login); scratch orgs (dx-org-manage)./platform-apex-anonymous-runRuns anonymous Apex against the connected org (.apex file or pasted snippet), capturing the debug log, surfacing errors. Triggers on "run this anonymous apex", "execute this script against my org", "what does this code return", or "execute scripts/foo.apex". Wraps scripts in savepoint+rollback; warns before running in production. DO NOT TRIGGER for authoring .cls/.trigger files (platform-apex-generate), Apex unit tests (platform-apex-test-run), or debug-log analysis (platform-apex-logs-debug)./platform-apex-generatePrimary Apex authoring skill for class generation, refactoring, and review. ALWAYS ACTIVATE when the user mentions Apex, .cls, triggers, or asks to create/refactor a class (service, selector, domain, batch, queueable, schedulable, invocable, DTO, utility, interface, abstract, exception, REST resource). Use this skill for requests involving SObject CRUD, mapping collections, fetching related records, scheduled jobs, batch jobs, trigger design, @AuraEnabled controllers, @RestResource endpoints, custom REST APIs, or code review of existing Apex./platform-apex-logs-debugSalesforce debug log analysis and troubleshooting with 100-point scoring. TRIGGER when: user analyzes debug logs, hits governor limits, reads stack traces, or touches .log files from Salesforce orgs. DO NOT TRIGGER when: running Apex tests (use platform-apex-test-run), generating or fixing Apex code (use platform-apex-generate), or Agentforce session tracing (use agentforce-observe).3 plugins in 2 repositories ship this exact skill · first indexed Nov 24, 2026
npx claudepluginhub forcedotcom/sf-skills --plugin salesforce-developmentOther plugins' skills for the same job