Agent skill

Platform Apex Test Generate

by forcedotcom in forcedotcom/sf-skills

A skill your agent uses to generate and validate Apex test classes with TestDataFactory patterns, bulk testing (251+ records), mocking, assertions, and disciplined test-fix loops.

Apache-2.0Auto-check passedTesting & QA

Install Platform Apex Test Generate

skills CLI
$ npx skills add forcedotcom/sf-skills --skill platform-apex-test-generate -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install forcedotcom/sf-skills platform-apex-test-generate --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/forcedotcom/sf-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/platform-apex-test-generate .claude/skills/platform-apex-test-generate && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
platform-apex-test-generate
GitHub stars
1.1k
Token cost
~2.5k tokens
SKILL.md length
827 words
Files
7 (incl. references, assets)
Skills in repo
251
Repo updated
First seen
Licence
Apache-2.0

At a glance

A skill your agent uses to generate and validate Apex test classes with TestDataFactory patterns, bulk testing (251+ records), mocking, assertions, and disciplined test-fix loops.

  • Works in 6 steps: Gather Context → Generate the Test Class → Run Tests → …
  • Generate and validate Apex test classes with TestDataFactory patterns
  • SKILL.md covers Core Principles, Test.startTest() /…, Test Code Anti-Patterns and Workflow, plus 3 more sections
  • Calls sf; reaches soap.sforce.com

What it does

Platform Apex Test Generate is an agent skill from forcedotcom/sf-skills. 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.

Its SKILL.md is about 2.5k tokens, which your agent loads only when the skill is triggered. The skill folder holds 8 other files, including reference files and assets (for example `references/assertion-patterns.md`, `references/async-testing.md` and `references/mocking-patterns.md`).

It sits in Testing & QA, covering Unit testing, Test coverage and Background jobs. It works with Jest. The repository describes itself as: Salesforce's curated collection of agent skills for building applications. Optimized for Agentforce Vibes, compatible with all AI tools. The licence is Apache-2.0.

When your agent uses it

  • Generate and validate Apex test classes with TestDataFactory patterns
  • Bulk testing (251+ records)
  • Disciplined test-fix loops
  • Creating Apex test classes (for triggers

Example prompts

  • “/platform-apex-test-generate”

Workflow steps

6 steps, taken from the step headings in SKILL.md.

  1. Gather Context
  2. Generate the Test Class
  3. Run Tests
  4. Analyze Results
  5. Fix Loop
  6. Validate Coverage

What it can do on your machine

Read from SKILL.md and the folder at commit e5164d9. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • sf

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • soap.sforce.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Platform Apex Test Generate loads about 2.5k tokens when it runs, and up to ~6.8k if it reads all its reference files. Until then it costs about 136 tokens; SKILL.md has 827 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~136
When it runs · the whole SKILL.md, loaded when a task matches
~2.5k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~6.8k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from forcedotcom/sf-skills at commit e5164d9, republished under its Apache-2.0 licence (© forcedotcom). 827 words, ~2,462 tokens.

Download SKILL.mdSave it as .claude/skills/platform-apex-test-generate/SKILL.md (or your agent's skills folder). This skill also uses 6 other files; get the full folder from GitHub.
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
metadata.domains
Platform
metadata.minApiVersion
66.0
metadata.relatedSkills
platform-apex-generate

Generating Apex Tests

Generate production-ready Apex test classes and run disciplined test-fix loops with coverage analysis.

Core Principles

  1. 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
  2. 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 set batchSize >= testRecordCount. See references/async-testing.md
  3. Isolate test data — every @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.md
  4. 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
  5. Use Assert class only — Assert.areEqual, Assert.isTrue, Assert.fail, etc. Never use legacy System.assert, System.assertEquals, or System.assertNotEquals
  6. Mock external boundaries — use HttpCalloutMock for callouts, Test.setFixedSearchResults for SOSL, DML mock classes for database isolation. Design for testability via constructor injection. See references/mocking-patterns.md
  7. Test negative paths — validate error handling and exception scenarios, not just happy paths
  8. Wrap with start/stop — pair Test.startTest() with Test.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-PatternFix
SOQL/DML inside loopsQuery once before the loop; use Map<Id, SObject> for lookups
Magic numbers in assertionsDerive 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 catchCatch 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:

  1. {ClassName}Test.cls — the test class (use assets/test-class-template.cls as starting point)
  2. {ClassName}Test.cls-meta.xml — the metadata file:
xml
<?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
apex
@TestSetup
static void setupTestData() {
    List<Account> accounts = TestDataFactory.createAccounts(251, true);
}
Test Method Structure

Use Given/When/Then:

apex
@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:

apex
@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.

bash
# 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>
Show full SKILL.md (353 more words)Show less
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):

  1. Read the failing test class and the class under test
  2. Identify root cause from error messages and stack traces
  3. Apply fix — adjust test data or assertions for test-side issues; delegate production code issues to the platform-apex-generate skill
  4. Rerun the focused test before broader regression
  5. Repeat until all tests pass, iteration limit reached, or root cause requires design change
Step 6 — Validate Coverage
LevelCoveragePurpose
Production deploy75% minimumRequired by Salesforce
Recommended90%+Best practice target
Critical paths100%Business-critical code

Cover all paths: positive, negative/exception, bulk (251+ records), callout/async.

What to Test by Component

ComponentKey Test Scenarios
TriggerBulk insert/update/delete, recursion guard, field change detection
ServiceValid/invalid inputs, bulk operations, exception handling
ControllerPage load, action methods, view state
Batchstart/execute/finish, scope matching (batch size >= record count), Database.Stateful tracking, error handling, chaining (separate methods — finish() calling Database.executeBatch() throws UnexpectedException)
QueueableChaining (only first job runs in tests), bulkification, error handling, callout mocks before Test.startTest()
CalloutSuccess response, error response, timeout
SelectorValid/null/empty inputs, bulk (251+), field population, sort order, WITH USER_MODE via System.runAs
ScheduledDirect execution via execute(null), CRON registration via CronTrigger query
Platform EventTest.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; default 66.0)
  • TestDataFactory.cls + TestDataFactory.cls-meta.xml (if not already present)

Reference Files

Load on demand for detailed patterns:

ReferenceWhen to use
references/test-data-factory.mdTestDataFactory patterns, field overrides, duplicate rule handling
references/assertion-patterns.mdAssertion best practices, anti-patterns, common pitfalls
references/mocking-patterns.mdHttpCalloutMock, DML mocking, StubProvider, SOSL, Email, Platform Events
references/async-testing.mdBatch, Queueable, Future, Scheduled job testing

© forcedotcom, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 6 other files (references, assets) in skills/platform-apex-test-generate of forcedotcom/sf-skills.

  • SKILL.md
  • assets/test-class-template.cls
  • assets/test-data-factory-template.cls
  • references/assertion-patterns.md
  • references/async-testing.md
  • references/mocking-patterns.md
  • references/test-data-factory.md

Open the folder on GitHubat commit e5164d9

Compare with similar skills

Platform Apex Test Generate next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Platform Apex Test Generate compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Platform Apex Test Generate this skillforcedotcom/sf-skills1.1k—~2.5kAutomated safety check: PassApache-2.0
Write Testsgrafana/synthetic-monitoring-app171—~1.2kAutomated safety check: PassAGPL-3.0
Write Testsopenplayerjs/openplayerjs649—~1.8kAutomated safety check: PassMIT
Bun Testinvolvex/youtube-music-cli456—~2.3kAutomated safety check: NotesMIT
Test Specialisttravisjneuman/.claude101—~3.7kAutomated safety check: PassMIT
Senior QAalirezarezvani/claude-skills28k1 repos~2.1kAutomated safety check: PassMIT

Similar skills

  • Write Tests

    grafana/synthetic-monitoring-app

    Official

    Write Jest integration and unit tests for the Grafana Synthetic Monitoring app using React Testing Library, MSW, and src/test helpers.

    171 GitHub stars~1.2k tokensUpdated today
    Testing & QAAuto-check passed
  • Write Tests

    openplayerjs/openplayerjs

    Write or extend Jest tests for OpenPlayerJS to this repo's exact conventions — makeCore factories, typed internals handles instead of as any, media property mocking, fake timers, ads/vast mocks, and…

    649 GitHub stars~1.8k tokensUpdated 2 days ago
    Testing & QAAuto-check passed
  • Bun Test

    involvex/youtube-music-cli

    Configure Bun's built-in test runner with Jest-compatible APIs.

    456 GitHub stars~2.3k tokensUpdated today
    Testing & QAAuto-check: notes
  • Test Specialist

    travisjneuman/.claude

    Test-writing patterns for JS/TS, Python, Go, and Rust (unit, integration, E2E, visual regression).

    101 GitHub stars~3.7k tokensUpdated 2 days ago
    Testing & QAAuto-check passed
  • Senior QA

    alirezarezvani/claude-skills

    Generates unit tests, integration tests, and E2E tests for React/Next.js applications.

    28k GitHub starsUsed in 1 repo~2.1k tokens
    Testing & QAAuto-check passed
  • TDD Guide

    alirezarezvani/claude-skills

    Test-driven development skill for writing unit tests, generating test fixtures and mocks, analyzing coverage gaps, and guiding red-green-refactor workflows across Jest, Pytest, JUnit, Vitest, and…

    28k GitHub stars~3.4k tokensUpdated 1 mo ago
    Testing & QAAuto-check passed

More from forcedotcom/sf-skills

All 251 skills in this repo
  • Agentforce Architecture Analyze

    forcedotcom/sf-skills

    Declared architecture snapshot for one Agentforce agent: planner, topics, actions, flows, Apex, prompt templates, and NGA plugins.

    1.1k GitHub stars~4.5k tokensUpdated yesterday
    Auto-check passed
  • Agentforce D360 Analyze

    forcedotcom/sf-skills

    Data Cloud 360° view of a single Agentforce session. An agent skill from forcedotcom/sf-skills.

    1.1k GitHub stars~3.4k tokensUpdated yesterday
    Auto-check passed
  • Apply a Salesforce sandbox post-copy automation JSON config against a target org.

    1.1k GitHub stars~5.3k tokensUpdated yesterday
    Auto-check: notes
  • Apply a Salesforce sandbox post-copy automation JSON config against a target org.

    1.1k GitHub stars~5.4k tokensUpdated yesterday
    Auto-check: notes
  • Design Systems Slds Apply

    forcedotcom/sf-skills

    Apply SLDS-compliant UI using the correct blueprints, styling hooks, utility classes, and icons.

    1.1k GitHub stars~3.7k tokensUpdated yesterday
    Auto-check passed
  • Experience Lwc Generate

    forcedotcom/sf-skills

    Lightning Web Components with PICKLES methodology and 165-point scoring.

    1.1k GitHub stars~2.4k tokensUpdated yesterday
    Auto-check passed

Works with

Categories

Questions about Platform Apex Test Generate

What does Platform Apex Test Generate do?

A skill your agent uses to generate and validate Apex test classes with TestDataFactory patterns, bulk testing (251+ records), mocking, assertions, and disciplined test-fix loops. Platform Apex Test Generate is an agent skill from forcedotcom/sf-skills. Use to generate and validate Apex test classes with TestDataFactory patterns, bulk testing (251+ records), mocking, assertions, and disciplined test-fix loops.

When should I use Platform Apex Test Generate?

Platform Apex Test Generate fits situations like: generate and validate Apex test classes with TestDataFactory patterns; bulk testing (251+ records); disciplined test-fix loops; creating Apex test classes (for triggers.

How do I install Platform Apex Test Generate in Claude Code?

Run `npx skills add forcedotcom/sf-skills --skill platform-apex-test-generate -a claude-code`. Or copy the skill folder (skills/platform-apex-test-generate in forcedotcom/sf-skills) into .claude/skills/platform-apex-test-generate in your project. Claude Code loads it when a task matches its description.

How do I install Platform Apex Test Generate in Codex?

Run `npx skills add forcedotcom/sf-skills --skill platform-apex-test-generate -a codex`. Or copy the skill folder (skills/platform-apex-test-generate in forcedotcom/sf-skills) into .agents/skills/platform-apex-test-generate in your project. Codex loads it when a task matches its description.

Can I use Platform Apex Test Generate in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add forcedotcom/sf-skills --skill platform-apex-test-generate -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/platform-apex-test-generate, .gemini/skills/platform-apex-test-generate, .github/skills/platform-apex-test-generate and .opencode/skills/platform-apex-test-generate in your project.

What does Platform Apex Test Generate need to run?

Going by SKILL.md and its folder, Platform Apex Test Generate needs the command-line tools its instructions call (sf).

Does Platform Apex Test Generate access the network?

SKILL.md names 1 domain. In commands or code: soap.sforce.com; the agent is likely to contact it when it follows the instructions. This is read from the text; nothing was executed.

Is Platform Apex Test Generate safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Platform Apex Test Generate use?

Platform Apex Test Generate is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Platform Apex Test Generate use?

About 2.5k tokens (SKILL.md is roughly 9.8k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 4.4k tokens, read only when the agent opens those files.

What are the alternatives to Platform Apex Test Generate?

Skills that share tags, products or a category with Platform Apex Test Generate: Write Tests (grafana/synthetic-monitoring-app, 171 stars), Write Tests (openplayerjs/openplayerjs, 649 stars), Bun Test (involvex/youtube-music-cli, 456 stars) and Test Specialist (travisjneuman/.claude, 101 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Platform Apex Test Generate?

forcedotcom (a GitHub organization) maintains it in forcedotcom/sf-skills, which has 1,060 GitHub stars. The repository holds 251 skills in this directory. The repository was last updated on October 7, 2026.

Source: forcedotcom/sf-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.