grzmol/vibe-force/sf-apex-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.

Writes and repairs Salesforce Apex unit tests — @IsTest classes and methods, @TestSetup, Test.startTest/Test.stopTest limit contexts, System.runAs for user-context and FLS/CRUD negative tests, the modern Assert class (Assert.areEqual, isTrue, isNull, isInstanceOfType, fail) versus legacy System.assertEquals, test data factory and builder patterns, Test.loadData with static resources, HttpCalloutMock, StaticResourceCalloutMock, MultiStaticResourceCalloutMock, WebServiceMock, Test.setMock, the Stub API (System.StubProvider and Test.createStub), asynchronous testing of Queueable, Batch, future and Schedulable jobs, Test.getEventBus().deliver() for platform events, Test.enqueueBatchJobs, 200-record bulk trigger tests, code coverage rules and the 75% deployment requirement, sf apex run test flag selection, test suites, flaky-test diagnosis, and how vf-check apex gates apexOrgCoverageMin and apexClassCoverageMin. Use this skill when creating or fixing a *Test.cls, when coverage or a deployment test level blocks a release, when a test is flaky or org-data dependent, or before running vf-check apex or sf apex run test.

Install

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

SKILL.md

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

Apex Testing

Coverage and test-level rules below are platform requirements; the numeric gates are vibe-force policy from .vibeforce/config.json.

RuleValueSource
Platform minimum coverage to deploy or package Apex75% of Apex code, all tests passingApex Developer Guide
Platform per-class minimum under RunSpecifiedTests75% per class and per trigger, computed individuallySalesforce CLI reference
Every trigger must have some coveragenon-negotiableApex Developer Guide
vibe-force org coverage gategates.apexOrgCoverageMin = 85config/vibe-force.defaults.json
vibe-force per-class coverage gategates.apexClassCoverageMin = 75config/vibe-force.defaults.json
New Apex class requires a test classgates.requireTestForApexClass = trueconfig/vibe-force.defaults.json

Not counted as covered: System.debug calls, test methods, and test classes. Conditional and ternary operators count as executed only when both branches run.

When to use

  • Creating or repairing any *Test.cls, or a deployment fails its test level.
  • Coverage is below a gate, or differs between sandbox and production.
  • A test is flaky, order-dependent, or reads org data.
  • Asynchronous work (Queueable, Batch, future, Schedulable, platform events) needs deterministic

assertions.

  • A callout, an external service, or a collaborator class must be mocked.

Adjacent skills: sf-apex-development (code under test), sf-async-apex-patterns (job design), sf-governor-limits (Limits assertions), sf-security-model (permission sets for negative tests), sf-lwc-jest-testing (client tests), sf-deployment-strategies (test levels per environment), sf-debugging-logs (diagnosing a failing test).

Decision table

SituationDo this
Shared records for every method in the class@TestSetup static void setup() — rolled back after each test method
Records must exist before the code under test runscreate them before Test.startTest()
Need a clean governor-limit budget for the assertion windowwrap the exercise in Test.startTest() / Test.stopTest()
Async job must complete before assertionsenqueue inside the startTest/stopTest block; assert after stopTest()
Platform event must be deliveredTest.getEventBus().deliver(); after Test.stopTest()
Callout in the code pathTest.setMock(HttpCalloutMock.class, new XMock());
Collaborator class must return canned dataStub API: Test.createStub(IFoo.class, provider)
Collaborator is static, private, inner, a trigger, or BatchableStub API cannot mock it — inject an interface instead
SOSL must return known rowsTest.setFixedSearchResults(ids) — SOSL otherwise returns empty in tests
Verify behaviour for a restricted userSystem.runAs(u) { ... } with a permission-set-assigned user
Mixed DML (setup object plus normal object)wrap in System.runAs(thisUser) { ... }
Field is not writable from Apex (e.g. CreatedDate)Test.setCreatedDate(recordId, dt)
Must read existing org dataavoid; if truly unavoidable @IsTest(SeeAllData=true) and document why
Bulk behaviour200 records — the documented Apex trigger batch size

Core patterns

1. Test class anatomy
apex
@IsTest
private class CaseEscalationServiceTest {
@TestSetup
static void makeData() {
// Runs once per test method, before it; changes roll back afterwards.
insert new List<Account>{
new Account(Name = 'Platinum Co', Tier__c = 'Platinum'),
new Account(Name = 'Standard Co', Tier__c = 'Standard')
};
}
@IsTest
static void escalatesPlatinumCaseToHigh() {
Account platinum = [SELECT Id, OwnerId FROM Account WHERE Tier__c = 'Platinum' LIMIT 1];
Case c = new Case(Subject = 'Outage', Priority = 'Low', AccountId = platinum.Id);
insert c;
Test.startTest();
CaseEscalationService.escalate(new List<Case>{ c });
Test.stopTest();
Case after = [SELECT Priority, OwnerId FROM Case WHERE Id = :c.Id];
Assert.areEqual('High', after.Priority, 'Platinum tier must escalate to High');
Assert.areEqual(platinum.OwnerId, after.OwnerId, 'Case should transfer to the account owner');
}
}

@IsTest classes must be top-level, cannot be interfaces or enums, and their access modifiers are irrelevant — the framework finds the methods regardless. @IsTest code is excluded from the 6 MB org code limit and from coverage arithmetic. Static member values changed in a @TestSetup or test method are not preserved for other methods in the class. @TestSetup is unsupported in a class annotated @IsTest(SeeAllData=true).

2. Test.startTest / Test.stopTest semantics

Both may be called at most once per test method.

BehaviourDetail
Limit contextcode between the two calls receives a new set of governor limits; startTest adds a context rather than refreshing it, so limits consumed before it are restored after stopTest
Asynchronous flushall async calls made after startTest are collected and run synchronously at stopTest
Exception during flushhalts the synchronous processing — for example an unhandled exception in a batch execute prevents finish from running
Savepointsfrom API 60.0, all savepoints are released when startTest and stopTest are called; a SAVEPOINT_RESET event is logged

Arrange before startTest, act between, assert after stopTest.

3. Assertions

Use the Assert class. System.assert* still compiles but carries no message discipline and is legacy.

LegacyModern
System.assertEquals(a, b)Assert.areEqual(a, b, 'why')
System.assertNotEquals(a, b)Assert.areNotEqual(a, b, 'why')
System.assert(cond)Assert.isTrue(cond, 'why')
System.assert(!cond)Assert.isFalse(cond, 'why')
System.assert(x == null)Assert.isNull(x, 'why')
System.assert(x != null)Assert.isNotNull(x, 'why')
System.assert(false, 'unreachable')Assert.fail('DmlException expected')
no equivalentAssert.isInstanceOfType(o, Account.class) / Assert.isNotInstanceOfType(...)

Argument order is (expected, actual, message). Negative tests assert the failure, not merely that something threw:

apex
@IsTest
static void rejectsNegativeAmount() {
Opportunity o = new Opportunity(
Name = 'Bad', StageName = 'Prospecting', CloseDate = Date.today(), Amount = -1
);
try {
insert o;
Assert.fail('Expected a DmlException for a negative Amount');
} catch (DmlException e) {
Assert.areEqual(1, e.getNumDml(), 'Exactly one record should fail');
Assert.isTrue(
e.getDmlMessage(0).contains('Amount'),
'Error must name the offending field, got: ' + e.getDmlMessage(0)
);
}
}

Full Assert API table in references/assertions-and-mocks.md.

4. Test data factory

Public @IsTest utility classes are excluded from the org code limit and callable only from test context. Build records; never read org data.

apex
@IsTest
public class TestDataFactory {
public static List<Account> accounts(Integer count, String tier) {
List<Account> out = new List<Account>();
for (Integer i = 0; i < count; i++) {
out.add(new Account(Name = 'Acct ' + i, Tier__c = tier));
}
insert out;
return out;
}
public static List<Case> cases(Integer perAccount, List<Account> accounts) {
List<Case> out = new List<Case>();
for (Account a : accounts) {
for (Integer i = 0; i < perAccount; i++) {
out.add(new Case(Subject = 'C' + i, Priority = 'Low', AccountId = a.Id));
}
}
insert out;
return out;
}
}

Tests are isolated from org data by default — @IsTest(SeeAllData=false) is the implicit behaviour for API 24.0 and later. SeeAllData=true at class level cannot be overridden by a method-level false, and it is incompatible with IsParallel=true. Builders, Test.loadData with static resources, and Test.setCreatedDate recipes are in references/test-patterns.md.

5. Mocking callouts and collaborators

Tests do not support HTTP callouts; without a mock the test fails.

apex
@IsTest
private class PaymentsClientTest {
private class Mock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
Assert.areEqual('callout:Payments/charge', req.getEndpoint());
Assert.areEqual('POST', req.getMethod());
HttpResponse res = new HttpResponse();
res.setStatusCode(201);
res.setHeader('Content-Type', 'application/json');
res.setBody('{"id":"ch_1","status":"succeeded"}');
return res;
}
}
@IsTest
static void chargeReturnsProviderId() {
Test.setMock(HttpCalloutMock.class, new Mock());
Test.startTest();
String chargeId = PaymentsClient.charge(1000, 'USD');
Test.stopTest();
Assert.areEqual('ch_1', chargeId, 'Client must surface the provider charge id');
}
}

Mock selection:

NeedMock
One endpoint, logic in ApexHttpCalloutMock implementation
Response body held as a static resourceStaticResourceCalloutMock
Several endpoints, each with its own static resourceMultiStaticResourceCalloutMock
SOAP callout from a WSDL2Apex stubWebServiceMock
Collaborator Apex classStub API — System.StubProvider plus Test.createStub

Stub API limitations shape design: it cannot mock static methods (including future methods), private methods, properties, triggers, inner classes, system types, classes implementing Batchable, or classes with only private constructors; iterators cannot be return or parameter types; and the mocked object must live in the same namespace as the Test.createStub() call. A multi-endpoint router and a full StubProvider are in references/assertions-and-mocks.md.

6. Asynchronous tests
apex
@IsTest
private class InvoiceSyncQueueableTest {
@IsTest
static void queueableMarksInvoicesSynced() {
List<Invoice__c> invoices = TestDataFactory.invoices(5);
Test.setMock(HttpCalloutMock.class, new InvoiceSyncMock());
Test.startTest();
System.enqueueJob(new InvoiceSyncQueueable(new Map<Id, Invoice__c>(invoices).keySet()));
Test.stopTest(); // job runs synchronously here
Assert.areEqual(
5,
[SELECT COUNT() FROM Invoice__c WHERE Sync_Status__c = 'Synced'],
'Every queued invoice should be marked synced'
);
}
}
Async featureTest techniqueConstraint
QueueableSystem.enqueueJob inside startTest/stopTestchaining is not executed in tests beyond the first job
Batch ApexDatabase.executeBatch inside the blockmax 5 batch jobs submitted per running test; only one execute chunk runs
Future methodcall the method inside the block@Future cannot be invoked from another @Future
SchedulableSystem.schedule inside the block; job runs at stopTestcron string still required
Flex queue orderingTest.enqueueBatchJobs(n) plus Test.getFlexQueueOrder()enqueues no-operation jobs for ordering assertions
Platform eventsTest.getEventBus().deliver(); after Test.stopTest()one deliver() per downstream publishing hop
BatchApexErrorEventDatabase.RaisesPlatformEvents on the batch class, then deliver()wrap the block in try/catch to swallow the job's exception

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

Security

  • Security scanPassed, 100 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-apex-testing/badge)](https://verified-skill.com/skills/grzmol/vibe-force/sf-apex-testing)

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