platform-apex-test-generate
forcedotcom/sf-skills
Generate and validate Apex test classes with TestDataFactory patterns, bulk testing, mocking, and coverage analysis.
What is platform-apex-test-generate?
Generates production-ready Apex test classes following Salesforce best practices, including TestDataFactory patterns, bulk testing (251+ records), mocking, assertions, and disciplined test-fix loops. Use when creating or improving Apex test classes for triggers, services, controllers, batch jobs, queueables, and callouts, or when debugging failing tests and analyzing coverage.
- Generate test classes with one behavior per method and separate positive, negative, and bulk test scenarios
- Create TestDataFactory classes for isolated, reusable test data setup
- Implement bulkified tests with 251+ records to cross the 200-record trigger batch boundary
- Apply mocking patterns for external boundaries (HttpCalloutMock, SOSL, DML isolation)
- Run disciplined test-fix loops with coverage analysis and focused debugging
- Validate assertions with exact expected values and meaningful failure messages
How to install platform-apex-test-generate
npx skills add https://github.com/forcedotcom/sf-skills --skill platform-apex-test-generate- Salesforce CLI (sf) version 2.0.0 or higher
- API version 66.0 or higher in org
- Existing production Apex classes to test (triggers, services, controllers, batch jobs, queueables, callouts)
How to use platform-apex-test-generate
- 1.Gather context: identify target production class(es), existing test classes, test data factories, and coverage threshold
- 2.Generate test class using the template structure with Given/When/Then pattern and one behavior per method
- 3.Create TestDataFactory class if none exists to handle isolated test data setup
- 4.Run focused tests with sf apex run test command against target org
- 5.Analyze results for failing methods, uncovered lines, and weak coverage areas
- 6.Execute disciplined fix loop (max 3 iterations) to address test failures or coverage gaps
Use cases
- Creating new Apex test classes for triggers, services, controllers, batch jobs, queueables, and callouts
- Improving code coverage from baseline to 75% minimum or 90%+ recommended targets
- Debugging and fixing failing Apex tests with root-cause analysis and iterative fixes
- Analyzing coverage reports to identify uncovered lines and weak coverage areas
- Testing async operations (batch Apex, queueables, future methods) with proper Test.startTest/stopTest wrapping
- Salesforce developers writing Apex test classes
- QA engineers validating Apex code coverage and test quality
- Platform engineers maintaining trigger and service test suites
- Developers improving test coverage before production deployments
platform-apex-test-generate FAQ
Use platform-apex-test-generate for Apex test classes (*Test.cls files), test data factories, and coverage analysis. Use platform-apex-generate for production Apex code (triggers, services, controllers, batch jobs). Do NOT use this skill for Jest/LWC tests.
Salesforce requires 75% minimum coverage for production deployment. Best practice is 90%+ coverage, with 100% coverage for business-critical code paths.
In test context, only one execute() invocation runs. Set batchSize >= testRecordCount and use Test.startTest/stopTest to force synchronous execution. See references/async-testing.md for details.
Use the Assert class only (Assert.areEqual, Assert.isTrue, Assert.fail, etc.). Never use legacy System.assert, System.assertEquals, or System.assertNotEquals.
Use HttpCalloutMock to mock external boundaries. Design production code for testability via constructor injection. See references/mocking-patterns.md for patterns.
Full instructions (SKILL.md)
Source of truth, from forcedotcom/sf-skills.
name: platform-apex-test-generate description: "Use to generate and validate Apex test classes with TestDataFactory patterns, bulk testing (251+ records), mocking, assertions, and disciplined test-fix loops. Use when creating Apex test classes (for triggers, services, controllers, batch jobs, queueables, and callouts), improving coverage, debugging or fixing failing Apex tests, or running test/coverage analysis. Triggers on *Test.cls files, sf apex run test, coverage reports. Do NOT trigger for production Apex (use platform-apex-generate) or Jest/LWC tests." metadata: version: "1.1" domains: ["Platform"] minApiVersion: "66.0" relatedSkills: - "platform-apex-generate" cliTools: - tool: ["sf"] semver: ">=2.0.0"
Generating Apex Tests
Generate production-ready Apex test classes and run disciplined test-fix loops with coverage analysis.
Core Principles
- One behavior per method — each test method validates a single scenario. Separate positive, negative, and bulk tests. NEVER combine related-but-distinct inputs (e.g., null and empty) in one method — create
_NullInput_and_EmptyInput_as separate test methods - Bulkify tests — test with 251+ records to cross the 200-record trigger batch boundary. Batch Apex exception: in test context only one
execute()invocation runs, so setbatchSize >= testRecordCount. See references/async-testing.md - Isolate test data — every
@TestSetupmust delegate record creation to aTestDataFactoryclass. 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.md - Assert meaningfully — use exact expected values computed from test data setup. NEVER use range assertions or approximate counts when the value is deterministic. Always include failure messages. See references/assertion-patterns.md
- Use
Assertclass only —Assert.areEqual,Assert.isTrue,Assert.fail, etc. Never use legacySystem.assert,System.assertEquals, orSystem.assertNotEquals - Mock external boundaries — use
HttpCalloutMockfor callouts,Test.setFixedSearchResultsfor SOSL, DML mock classes for database isolation. Design for testability via constructor injection. See references/mocking-patterns.md - Test negative paths — validate error handling and exception scenarios, not just happy paths
- Wrap with start/stop — pair
Test.startTest()withTest.stopTest()to reset governor limits and force async execution
Test.startTest() / Test.stopTest()
Always wrap the code under test in Test.startTest() / Test.stopTest():
- Resets governor limits so the test measures only the code under test
- Executes async operations synchronously (queueables, batch, future methods)
- Fires scheduled jobs immediately
Test Code Anti-Patterns
| 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) |
Workflow
Step 1 — Gather Context
Before generating or fixing tests, identify:
- the target production class(es) under test
- existing test classes, test data factories, and setup helpers
- desired test scope (single class, specific methods, suite, or local tests)
- coverage threshold (75% minimum for deploy, 90%+ recommended)
- org alias when running tests against an org
Step 2 — Generate the Test Class
Apply 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 Example
@TestSetup
static void setupTestData() {
List<Account> accounts = TestDataFactory.createAccounts(251, true);
}
Test Method Structure
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');
}
Negative Test — Exception Pattern
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();
}
Naming Convention
should[ExpectedResult]_When[Scenario]:shouldSendNotification_WhenOpportunityClosedWon[SubjectOrAction]_[Scenario]_[ExpectedResult]:AccountUpdate_ChangeName_Success
Step 3 — Run Tests
Start 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>
Step 4 — Analyze Results
Focus on:
- failing methods — exception types and stack traces
- uncovered lines and weak coverage areas
- whether failures indicate bad test data, brittle assertions, or broken production logic
- when class metadata crosses from versions 66.0 and below to 67.0 and above, check explicit sharing, decide user/system mode per operation, grant required CRUD/FLS in test users or permission sets, and rerun affected tests
Step 5 — Fix Loop
When tests fail, run a disciplined fix loop (max 3 iterations — stop and surface root cause if still failing):
- Read the failing test class and the class under test
- Identify root cause from error messages and stack traces
- Apply fix — adjust test data or assertions for test-side issues; delegate production code issues to the
platform-apex-generateskill - Rerun the focused test before broader regression
- Repeat until all tests pass, iteration limit reached, or root cause requires design change
Step 6 — Validate Coverage
| 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.
What to Test by Component
| 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 |
Output Expectations
Deliverables per test class:
{ClassName}Test.cls+{ClassName}Test.cls-meta.xml(match API version of class under test; default66.0)TestDataFactory.cls+TestDataFactory.cls-meta.xml(if not already present)
Reference Files
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 |
Related skills
More from forcedotcom/sf-skills and the wider catalog.

platform-apex-test-run
Run Apex tests, analyze coverage, and fix failures in Salesforce with structured test-fix loops.

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.