apex-mocking-and-stubs

Use when choosing or implementing Apex test doubles with `Test.setMock`, `HttpCalloutMock`, `StaticResourceCalloutMock`, or `StubProvider`, and when designing code seams to support those doubles cleanly. Triggers: 'StubProvider', 'Test.createStub', 'HttpCalloutMock', 'StaticResourceCalloutMock', 'mocking infrastructure'. NOT for general Apex test design outside the mocking and seam problem.

Best use case

apex-mocking-and-stubs is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Use when choosing or implementing Apex test doubles with `Test.setMock`, `HttpCalloutMock`, `StaticResourceCalloutMock`, or `StubProvider`, and when designing code seams to support those doubles cleanly. Triggers: 'StubProvider', 'Test.createStub', 'HttpCalloutMock', 'StaticResourceCalloutMock', 'mocking infrastructure'. NOT for general Apex test design outside the mocking and seam problem.

Teams using apex-mocking-and-stubs should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/apex-mocking-and-stubs/SKILL.md --create-dirs "https://raw.githubusercontent.com/PranavNagrecha/AwesomeSalesforceSkills/main/skills/apex/apex-mocking-and-stubs/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/apex-mocking-and-stubs/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How apex-mocking-and-stubs Compares

Feature / Agentapex-mocking-and-stubsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Use when choosing or implementing Apex test doubles with `Test.setMock`, `HttpCalloutMock`, `StaticResourceCalloutMock`, or `StubProvider`, and when designing code seams to support those doubles cleanly. Triggers: 'StubProvider', 'Test.createStub', 'HttpCalloutMock', 'StaticResourceCalloutMock', 'mocking infrastructure'. NOT for general Apex test design outside the mocking and seam problem.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

Use this skill when the main problem is not “write more tests” but “make this dependency replaceable in tests.” Apex mocking is split across transport-level mocks like `HttpCalloutMock` and seam-level stubs via `StubProvider`. The right choice depends on what is being replaced and whether the production code already has a clean boundary.

## Before Starting

- What exactly must be replaced: an HTTP callout, a SOAP/web-service call, or an internal collaborator?
- Does the production code expose an interface or virtual instance method boundary, or is everything static?
- Which scenarios matter: success, auth failure, timeout, malformed payload, retry exhaustion?

## Core Concepts

### `Test.setMock` Is For Platform-Level Outbound Behavior

Use `HttpCalloutMock`, `WebServiceMock`, or `StaticResourceCalloutMock` when the code under test interacts with a platform-managed transport. These mocks are ideal when the test needs to simulate the remote system’s response shape.

### `StubProvider` Is For Replaceable Collaborators

`Test.createStub` with `StubProvider` is useful when the dependency is an Apex collaborator that can be represented by an interface or class seam. This supports behavior-focused tests without branching on `Test.isRunningTest()`.

### The Seam Matters More Than The Mock

If the production code uses static utility methods and hardcoded constructors everywhere, the test framework is not the real issue. The design seam is. Good mocking in Apex starts with injectable or overridable boundaries.

### Mock Variety Beats Single Happy-Path Doubles

One success mock is not enough. Reliable tests exercise failure modes, retries, and malformed responses too. The point of mocking infrastructure is control, not just convenience.

## Common Patterns

### Scenario-Specific `HttpCalloutMock`

**When to use:** Callout behavior changes with status code or payload.

**How it works:** Create separate mocks for success, auth failure, timeout-like exceptions, and invalid payloads.

**Why not the alternative:** One universal mock hides error-path bugs.

### Static Resource Mock For Stable Payload Fixtures

**When to use:** Response bodies are large, fixed, and easier to keep as sample files.

**How it works:** Use `StaticResourceCalloutMock` to return known payloads without embedding massive JSON in the test.

### Interface + StubProvider Seam

**When to use:** Business services depend on an internal collaborator rather than a raw transport.

**How it works:** Define an interface or stub-friendly class, then use `Test.createStub` to control return values and behavior in tests.

## Decision Guidance

| Situation | Recommended Approach | Reason |
|---|---|---|
| Need to simulate outbound HTTP responses | `HttpCalloutMock` | Purpose-built for HTTP transport behavior |
| Need large static response fixtures | `StaticResourceCalloutMock` | Cleaner payload management in tests |
| Need to replace an internal collaborator | `StubProvider` + `Test.createStub` | Better seam-level control than transport mocks |
| Production code only offers static helpers | Refactor seam first, then mock | Missing seam is the real blocker |


## Recommended Workflow

Step-by-step instructions for an AI agent or practitioner activating this skill:

1. Gather context — confirm the org edition, relevant objects, and current configuration state
2. Review official sources — check the references in this skill's well-architected.md before making changes
3. Implement or advise — apply the patterns from Core Concepts and Common Patterns sections above
4. Validate — run the skill's checker script and verify against the Review Checklist below
5. Document — record any deviations from standard patterns and update the template if needed

---

## Review Checklist

- [ ] Mock choice matches the dependency type, not team habit.
- [ ] Tests cover at least one failure mode, not only success.
- [ ] Internal collaborators have interface or overridable seams where needed.
- [ ] No production branching exists solely to bypass dependencies in tests.
- [ ] Static resource mocks are used when fixture payload size justifies them.
- [ ] Mock classes remain focused and readable rather than becoming mini-frameworks.

## Salesforce-Specific Gotchas

1. **`StubProvider` does not rescue a design with only static dependencies** — the seam still has to exist.
2. **Transport mocks and seam stubs solve different problems** — do not use `HttpCalloutMock` to fake internal services.
3. **One global success mock can create false confidence** — retry and failure logic stay untested.
4. **Static resource mocks improve readability, but can hide contract drift if the payload is never reviewed** — keep fixtures intentional.

## Output Artifacts

| Artifact | Description |
|---|---|
| Mocking strategy | Recommendation for `Test.setMock`, static-resource fixtures, or `StubProvider` seams |
| Test-double review | Findings on seam quality and missing failure scenarios |
| Mock scaffold | Focused example for callout or collaborator substitution |

## Related Skills

- `apex/test-class-standards` — use when the broader testing design is the real issue and mocking is only one symptom.
- `apex/callouts-and-http-integrations` — use when the hardest part is the outbound HTTP contract itself.
- `apex/apex-design-patterns` — use when missing interfaces or injectable boundaries are blocking good mocks.

Related Skills

apex-managed-sharing-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Grant row-level access programmatically via __Share records when declarative sharing rules cannot express the policy. NOT for OWD, role hierarchy, or criteria-based sharing rule design.

lwc-imperative-apex

8
from PranavNagrecha/AwesomeSalesforceSkills

Call Apex methods imperatively from LWC — on button click, lifecycle hooks, or conditional logic. Covers import syntax, cacheable vs non-cacheable, async/await patterns, error handling, loading states, and Promise.all. NOT for wire service (use wire-service-patterns) and NOT for testing Apex mocks (use lwc-testing).

dataweave-for-apex

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when transforming structured data inside Apex — CSV → JSON, XML → SObject list, JSON → flattened CSV, or schema-mapping a third-party payload to a Salesforce model — and the existing options (`JSON.deserialize`, `Dom.Document`, hand-written loops) are getting unwieldy. Triggers: 'apex transform csv json xml without external library', 'system.dataweave script', 'salesforce native dataweave apex execute', 'transform xml to sobject apex no mulesoft', 'json reshape salesforce apex script'. NOT for MuleSoft Anypoint DataWeave running off-platform (use mulesoft-anypoint-architecture), NOT for Apex JSON serialization basics (use apex-json-serialization), NOT for Bulk API CSV ingest (use bulk-api-2-patterns).

flow-invocable-from-apex

8
from PranavNagrecha/AwesomeSalesforceSkills

Author @InvocableMethod Apex classes that Flow can call as Actions. Design the input / output variable contract, bulk semantics (one list in, one list out), null handling, and error surfacing. Also covers the inverse direction: calling a flow from Apex via Flow.Interview. NOT for general Apex authoring (use apex-service-selector-domain). NOT for REST-exposed Apex (use apex-rest-resource-patterns).

flow-apex-defined-types

8
from PranavNagrecha/AwesomeSalesforceSkills

Design and use Apex-Defined Types as Flow variables for structured non-sObject data (HTTP callout payloads, External Service responses, complex configuration). Trigger keywords: apex-defined type, flow variable, @AuraEnabled class, flow http callout response. Does NOT cover building HTTP Callout Actions themselves, External Services schema, or raw Apex invocable methods.

scheduled-apex-failure-detection-and-monitoring

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when nightly batch / scheduled Apex jobs are failing without anyone noticing — covers why uncaught exceptions in `execute()` go to the debug log instead of email, how to query `AsyncApexJob` for `Status`, `NumberOfErrors`, and `ExtendedStatus`, when to implement `Database.RaisesPlatformEvents` so the platform publishes `BatchApexErrorEvent` on uncaught failures, how to subscribe to that event with an Apex trigger and notify operators, and how to layer a custom watcher schedule on top so silent-failure modes (job that never started, scheduled class deleted, queue stuck on `Queued`) still surface. Triggers: 'nightly batch failed at 2am with no notification', 'how do we know if a scheduled apex job is failing', 'BatchApexErrorEvent vs custom retry logic', 'Setup Apex Jobs only shows last 7 days, where else can I look', 'job is stuck in queued status nobody noticed for a week'. NOT for general Apex exception handling patterns (use apex/apex-exception-handling-and-logging), NOT for Batch Apex authoring or chunking strategy (use apex/batch-apex-design), NOT for Setup → Apex Jobs UI walkthrough as an admin task (use admin/batch-job-scheduling-and-monitoring), NOT for retry logic itself (use apex/scheduled-apex-retry-patterns once authored).

platform-events-apex

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when publishing or subscribing to Salesforce Platform Events from Apex, comparing Platform Events with Change Data Capture, or designing event-triggered error handling and monitoring. Triggers: 'EventBus.publish', 'platform event trigger', 'CDC vs Platform Events', 'replay ID', 'high-volume event'. NOT for Flow-only publish/subscribe automation.

health-cloud-apex-extensions

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill when extending Health Cloud via Apex: implementing HealthCloudGA managed-package interfaces, automating care plan lifecycle hooks, processing referrals using Industries Common Components invocable actions, or enforcing HIPAA-compliant logging governance for clinical Apex code. Trigger keywords: CarePlanProcessorCallback, HealthCloudGA namespace, ReferralRequest, ReferralResponse, care plan invocable actions, clinical Apex extension, Health Cloud Apex API. NOT for standard Apex triggers or generic Apex development unrelated to Health Cloud managed-package extension points.

fsl-apex-extensions

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when writing Apex that calls Field Service Lightning scheduling APIs — AppointmentBookingService, ScheduleService, GradeSlotsService, or OAAS — to book, schedule, grade, or optimize service appointments programmatically. Trigger keywords: FSL Apex namespace, GetSlots, schedule service appointment via code, appointment booking API, FSL optimization API. NOT for standard Apex patterns unrelated to FSL, admin-level scheduling policy configuration, or declarative FSL scheduling.

fsc-apex-extensions

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill when extending Financial Services Cloud (FSC) behavior through Apex: customizing financial rollup recalculation, disabling built-in FSC triggers to write custom trigger logic, implementing Compliant Data Sharing (CDS) participant/role integrations, or building custom FSC action handlers. NOT for standard Apex unrelated to the FSC managed package, standard Salesforce sharing rules, or configuring FSC rollups through the Admin UI — use the admin/financial-account-setup skill for declarative rollup setup.

entitlement-apex-hooks

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill when writing Apex triggers or classes that interact with CaseMilestone records — completing milestones, detecting violations, or reacting to SLA state changes. Trigger keywords: CaseMilestone trigger, auto-complete milestone Apex, milestone violation polling, CompletionDate write pattern. NOT for entitlement process admin setup, milestone configuration in Setup UI, or Flow-based milestone actions.

dynamic-apex

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when building or reviewing code that constructs SOQL/SOSL at runtime, inspects schema metadata via Schema.describe methods, accesses fields dynamically on sObjects, or performs runtime type inspection. Triggers: 'Database.query', 'Schema.getGlobalDescribe', 'Schema.describeSObjects', 'dynamic field access', 'SObjectType', 'DescribeFieldResult'. NOT for static SOQL queries or query performance tuning — use soql-fundamentals or soql-query-optimization.