grzmol/vibe-force/sf-fflib-testing

Claude Code and agent skill by grzmol/vibe-force

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Covers every testing variant available in an Apex Enterprise Patterns (fflib) codebase - ApexMocks stub lifecycle (fflib_ApexMocks, startStubbing/when/thenReturn/stopStubbing, verify and verification modes), argument matchers and fflib_ArgumentCaptor, mock injection through Application.UnitOfWork/Service/Selector/Domain setMock, fake SObject graphs with fflib_ApexMocksUtils and fflib_IDGenerator, DML-free domain trigger tests via fflib_SObjectDomain.Test.Database, real-DML selector and integration tests, async/Queueable/Batch/Schedulable tests, platform-event delivery with Test.getEventBus().deliver(), callout mocks, and FLS/CRUD negative tests. Use when writing or reviewing any Apex test in a repo containing fflib_ApexMocks, fflib_SObjectSelector, fflib_SObjectDomain, fflib_SObjectUnitOfWork or an Application class, when a mock verification fails, when choosing between a mocked unit test and a real-DML integration test, or when Apex coverage gates (apexOrgCoverageMin 85 / apexClassCoverageMin 75) must be met without writing coverage-padding tests.

Install

npx vskill@latest install grzmol/vibe-force/sf-fflib-testing

SKILL.md

The same SKILL.md was published earlier as grzmol/vibe-force/sf-fflib-testing.

fflib Testing

Testing an fflib codebase means choosing, per class under test, between a mocked unit test (fast, proves collaboration, proves nothing about the org) and a real-DML test (slow, proves the platform actually behaves). Getting that choice wrong is the single largest source of worthless Apex test suites: 90% coverage where every selector's SOQL is unproven.

Framework grounding: fflib-apex-mocks @ master commit d81e9e1 and fflib-apex-common @ master commit dab5977 (both apex-enterprise-patterns). Platform grounding: Apex Developer Guide, Summer '26 / API version 67.0 (doc version 262.0) - the apiVersion in config/vibe-force.defaults.json.

Read sf-fflib-foundations for the Application/factory wiring these tests inject into, sf-fflib-selector-layer for selector construction, sf-fflib-domain-service-uow for the layers under test, and sf-fflib-operations for CI/packaging of the framework itself.

When to use

Use this skill when a repo contains fflib_ApexMocks, fflib_SObjectDomain, fflib_SObjectSelector, fflib_SObjectUnitOfWork, or an Application class, and you are:

  • writing a new test for a service, domain, selector, controller, trigger, or async job;
  • diagnosing an fflib_ApexMocks.ApexMocksException from verify(...) or when(...);
  • deciding whether a behaviour needs a mock or real DML;
  • raising coverage to clear the apex gate without adding tests that assert nothing.

For non-fflib Apex testing fundamentals (@IsTest, @TestSetup, System.runAs, Assert) see sf-apex-testing. For LWC component tests see sf-lwc-jest-testing. For limit budgets consumed by real-DML tests see sf-governor-limits.

Test-variant decision table

#VariantWhat it provesWhat it cannot proveSpeedOrg datafflib machineryCoverage contributionTypical failure mode
1Service unit test with mocksService orchestration: which selector/domain/UoW calls happen, in what shapeSOQL validity, triggers, FLS, validation rules~10-40 msnonefflib_ApexMocks, Application.*.setMock, fflib_MatchService impl class onlyOver-specified verify breaks on harmless refactor
2Domain unit test, no DML, direct constructionPure field logic on in-memory recordsTrigger routing, save order~5-20 msnonefflib_IDGenerator for ids; no mocks neededDomain classAsserting through the UoW mock instead of the record
3Domain trigger test via fflib_SObjectDomain.Test.DatabaseonApplyDefaults/onValidate/onBefore*/onAfter* routing and error registrationReal DML errors, validation rules, roll-ups, chained triggers~10-30 msnonefflib_SObjectDomain.Test.Database.onInsert/onUpdate/onDelete/onUndelete + fflib_SObjectDomain.triggerHandler(Type), fflib_SObjectDomain.ErrorsDomain + trigger handlerForgetting Errors.clearAll() between assertions in one method
4Selector test against real dataThe SOQL compiles, field list is right, filters and ordering workBehaviour of callers200 ms - 2 sinserted recordsReal selector, no mocks, fflib_QueryFactory outputSelector classMocking the selector - proves nothing
5Service integration test with real DMLEnd-to-end: service + domain + selector + UoW + triggers + validationIsolation of a single failure cause0.5-5 sinserted recordsApplication.UnitOfWork.newInstance(), no setMockEvery layer it crossesSlow suite; used as the only test style
6Trigger test with real DMLSave order, recursion, cross-object roll-ups, validation rulesNothing about isolated units0.5-3 sinserted recordsReal trigger + fflib_SObjectDomain.triggerHandlerTrigger + domainAssumes @TestSetup data survives Test.startTest() limits reset
7Controller / @AuraEnabled testWire adapter contract: return shape, AuraHandledException messagesClient rendering~20-80 ms mockednone if service mockedApplication.Service.setMock(IFooService.class, mock)Controller classTesting the service again through the controller
8Flow-invocable test (@InvocableMethod)Bulk request/response contract and per-row mappingFlow itself~20-80 msnone if service mockedApplication.Service.setMockInvocable classSingle-row-only test on a bulk API
9Async test: Queueable / SchedulableThe job enqueues, runs, and commits inside Test.startTest()/stopTest()Behaviour under real 2-minute chaining/limits0.5-3 susually yesReal UoW; mock the service the job calls where possibleJob classAsserting before Test.stopTest()
10Async test: Batchablestart/execute/finish wiring, one chunkMulti-chunk state, real scope sizes1-5 syesBatchable classes cannot be stubbed (Stub API limit) - mock its collaborators insteadBatch classExpecting finish after an unhandled execute exception in test context
11Platform-event testEvent publication and the subscriber triggerReal bus latency/replay0.3-2 ssometimesuow.registerPublishAfterSuccessTransaction, then Test.getEventBus().deliver()Publisher + subscriberMissing deliver(), so the subscriber never runs
12Callout testRequest shape and response handlingThe remote system~30-200 msnoneTest.setMock(HttpCalloutMock.class, ...) inside the mocked service boundaryCallout classCallout mock set after the callout is triggered
13FLS / CRUD negative testUSER_MODE DML and selector security actually rejectAnything under system mode0.5-3 suser + perm setfflib_SObjectUnitOfWork.UserModeDML, System.runAs, Assert.fail() + catch (SecurityException)Security pathsRunning as a System Administrator, so nothing is denied
14LWC Jest testClient behaviour, wire handling, DOMAny Apex~50-300 msnonenone (see sf-lwc-jest-testing)JS coverage (jestCoverageMin)Duplicating Apex assertions in JS

Rows 1-3, 7, 8 are the fast tier; rows 4-6, 9-13 are the slow tier. A healthy fflib org is roughly 70% fast tier / 25% slow tier / 5% end-to-end, described under "Test pyramid" below.

Core patterns

1. The ApexMocks lifecycle

fflib_ApexMocks implements System.StubProvider; mocks.mock(Type) returns Test.createStub(classToMock, this). The stub is named <Type>__sfdc_ApexStub, which is what you see in failure messages.

apex
@IsTest
private class OpportunitiesServiceTest {
@IsTest
static void applyDiscountRegistersDirtyOpportunities() {
// 1. Arrange the mock control object and the stubs
fflib_ApexMocks mocks = new fflib_ApexMocks();
IOpportunitiesSelector selectorMock = (IOpportunitiesSelector) mocks.mock(IOpportunitiesSelector.class);
fflib_ISObjectUnitOfWork uowMock = (fflib_ISObjectUnitOfWork) mocks.mock(fflib_ISObjectUnitOfWork.class);
Opportunity opp = new Opportunity(
Id = fflib_IDGenerator.generate(Opportunity.SObjectType),
Name = 'Test',
StageName = 'Open',
CloseDate = System.today(),
Amount = 1000);
Set<Id> oppIds = new Set<Id>{ opp.Id };
// 2. Stub: everything between startStubbing/stopStubbing records, it does not execute
mocks.startStubbing();
mocks.when(selectorMock.sObjectType()).thenReturn(Opportunity.SObjectType);
mocks.when(selectorMock.selectByIdWithProducts(oppIds)).thenReturn(new List<Opportunity>{ opp });
mocks.stopStubbing();
// 3. Inject
Application.Selector.setMock(selectorMock);
Application.UnitOfWork.setMock(uowMock);
// 4. Exercise the real implementation class, not the static facade
System.Test.startTest();
new OpportunitiesServiceImpl().applyDiscounts(new Map<Id, Decimal>{ opp.Id => 10 });
System.Test.stopTest();
// 5. Verify collaboration
((IOpportunitiesSelector) mocks.verify(selectorMock, 1)).selectByIdWithProducts(oppIds);
((fflib_ISObjectUnitOfWork) mocks.verify(uowMock, 1)).registerDirty(
fflib_Match.sObjectWith(new Map<SObjectField, Object>{
Opportunity.Id => opp.Id,
Opportunity.Amount => 900 }));
((fflib_ISObjectUnitOfWork) mocks.verify(uowMock, 1)).commitWork();
}
}

Rules that follow from the source:

  • Every `when(...)` must be inside `startStubbing()`/`stopStubbing()`. Outside it, the call is

recorded as a real invocation and then verified against later, corrupting counts.

  • **when(...) must be followed by thenReturn/thenThrow/thenAnswer/thenReturnMulti/

thenThrowMulti.** A bare when(...) yields ApexMocksException: The stubbing is not correct, no return values have been set. at call time.

  • Unstubbed methods return `null`, they do not throw. A NullPointerException deep inside the

class under test almost always means "you forgot to stub something".

  • `mocks.mock()` uses the Stub API, so the platform's stub limitations apply: no static or

private methods, no properties, no triggers, no inner classes, no system types, no Batchable implementers, no classes with only private constructors, and iterators cannot be a parameter or return type. The mocked type must be in the same namespace as the Test.createStub() call. (Apex Developer Guide, Build a Mocking Framework with the Stub API)

2. Generated mocks vs Stub API mocks

Two modes exist. Only the first is current.

ModeHow a mock is madeNeeds regeneration on interface changeUse
Stub API (current)(IFoo) mocks.mock(IFoo.class) -> Test.createStubNoDefault for everything
ApexMocks Generator (legacy)Pre-generated FooMocks.Foo class implementing the interface and delegating to mocks.mockNonVoidMethod(...) / mocks.mockVoidMethod(...)Yes - stale generated mocks silently driftOnly for types the Stub API refuses to stub

mockVoidMethod(Object, String, List<Type>, List<Object>) and mockNonVoidMethod(...) remain public on fflib_ApexMocks for generated classes. The generator itself is an external tool, not part of the fflib-apex-mocks repo.

fflib_ApexMocksConfig.HasIndependentMocks (default false) controls whether two mock instances of the same type share stubbing and counts. fflib_QualifiedMethod.equals/hashCode include the mock instance only when it is true. Set it to true in @IsTest setup when a single test holds two mocks of one interface and must distinguish them:

apex
fflib_ApexMocksConfig.HasIndependentMocks = true;
3. Verification API
apex
((IFoo) mocks.verify(fooMock)).bar(); // exactly 1
((IFoo) mocks.verify(fooMock, 3)).bar(); // exactly 3
((IFoo) mocks.verify(fooMock, fflib_ApexMocks.NEVER)).bar(); // NEVER == 0
((IFoo) mocks.verify(fooMock, mocks.atLeastOnce())).bar();
((IFoo) mocks.verify(fooMock, mocks.atLeast(2))).bar();
((IFoo) mocks.verify(fooMock, mocks.atMost(5))).bar();
((IFoo) mocks.verify(fooMock, mocks.between(1, 3))).bar();
((IFoo) mocks.verify(fooMock, mocks.times(2).description('two writes expected'))).bar();
fflib_InOrder inOrder = mocks.inOrder(new List<Object>{ fooMock, uowMock });
((IFoo) inOrder.verify(fooMock)).bar();
((fflib_ISObjectUnitOfWork) inOrder.verify(uowMock)).commitWork();
inOrder.verifyNoMoreInteractions();

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/grzmol/vibe-force/sf-fflib-testing/badge)](https://verified-skill.com/skills/grzmol/vibe-force/sf-fflib-testing)

Something wrong with this skill or its page? Tell us.