Testing Patterns
AT4DX's architecture makes testing straightforward because every dependency is injectable. This document covers how to test each layer in isolation and how to write integration tests when you need the full stack.
Testing Philosophy
The factory mock system is the key enabler:
Application.Selector.setMock(Account.SObjectType, mockSelector);
Application.Domain.setMock(mockDomain);
Application.Service.setMock(ISalesAccountsService.class, mockService);
Application.UnitOfWork.setMock(mockUow);
Any combination of these can be set before calling the code under test. The factory returns the mock instead of reading metadata. This means:
- Unit tests run entirely in memory — no DML, no SOQL, no metadata reads
- Each class is tested alone — Criteria, Actions, Services, and Domains each have a focused test
- Integration tests opt in to the full stack by not setting mocks
Testing Criteria in Isolation
Criteria classes are pure functions. They take records in and return a filtered list. No mocking needed.
@IsTest
private class LargeAccountCriteriaTest {
@IsTest
static void run_returnsOnlyAccountsAboveThreshold() {
List<SObject> input = new List<SObject>{
new Account(Name = 'HugeCo', AnnualRevenue = 5000000),
new Account(Name = 'MidCo', AnnualRevenue = 1000000), // exactly 1M — not large
new Account(Name = 'SmallCo', AnnualRevenue = 500000),
new Account(Name = 'NullCo', AnnualRevenue = null)
};
LargeAccountCriteria criteria = new LargeAccountCriteria();
criteria.setRecordsToEvaluate(input);
List<SObject> result = criteria.run();
System.assertEquals(1, result.size(), 'Only HugeCo exceeds 1M');
System.assertEquals('HugeCo', ((Account) result[0]).Name);
}
@IsTest
static void run_returnsEmptyListWhenNoRecordsMatch() {
List<SObject> input = new List<SObject>{
new Account(Name = 'SmallCo', AnnualRevenue = 100000)
};
LargeAccountCriteria criteria = new LargeAccountCriteria();
criteria.setRecordsToEvaluate(input);
List<SObject> result = criteria.run();
System.assert(result.isEmpty(), 'No accounts exceed threshold');
}
@IsTest
static void run_handlesNullAnnualRevenue() {
List<SObject> input = new List<SObject>{
new Account(Name = 'NullCo', AnnualRevenue = null)
};
LargeAccountCriteria criteria = new LargeAccountCriteria();
criteria.setRecordsToEvaluate(input);
List<SObject> result = criteria.run();
System.assert(result.isEmpty(), 'Null revenue should not match');
}
}
No mocks, no setup, no DML. These tests execute in microseconds.
Testing Sync Actions in Isolation
Drive the action exactly the way the coordinator does — setRecordsToActOn(...) then runInProcess() — and inspect the result. The MarkStrategicAccountAction runs in before context and mutates records in place, so it needs no Unit of Work.
@IsTest
private class MarkStrategicAccountActionTest {
@IsTest
static void runInProcess_setsStatusOnRecords() {
List<SObject> accounts = new List<SObject>{
new Account(Id = fflib_IDGenerator.generate(Account.SObjectType),
Name = 'BigCo', AnnualRevenue = 3000000)
};
MarkStrategicAccountAction action = new MarkStrategicAccountAction();
action.setRecordsToActOn(accounts);
action.runInProcess();
System.assertEquals('Strategic', ((Account) accounts[0]).Status__c);
}
@IsTest
static void runInProcess_handlesEmptyRecordList() {
MarkStrategicAccountAction action = new MarkStrategicAccountAction();
action.setRecordsToActOn(new List<SObject>());
action.runInProcess(); // should be a no-op without throwing
}
}
If an action stages DML against other records (an
after-context action with a Unit of Work), inject a mock withaction.setUnitOfWork(mockUow)and verify the AT4DXregister(...)calls withmocks.verify(...).
Testing Async Actions in Isolation
Async actions enqueue jobs. Verify the job was enqueued using Limits.getQueueableJobs() or check for the correct queueable being constructed, depending on your test strategy.
@IsTest
private class NotifyExternalSystemActionTest {
@IsTest
static void runInProcess_enqueuesJobForStrategicAccounts() {
List<Account> accounts = new List<Account>{
new Account(Id = fflib_IDGenerator.generate(Account.SObjectType),
Name = 'BigCo', AnnualRevenue = 5000000)
};
NotifyExternalSystemAction action = new NotifyExternalSystemAction();
action.setRecordsToActOn(accounts);
Test.startTest();
action.runInProcess();
Test.stopTest(); // flushes async queue
// 1 queueable was enqueued
System.assertEquals(1, Limits.getQueueableJobs(),
'One queueable job should have been enqueued');
}
@IsTest
static void runInProcess_doesNotEnqueueForEmptyList() {
NotifyExternalSystemAction action = new NotifyExternalSystemAction();
action.setRecordsToActOn(new List<SObject>());
Test.startTest();
action.runInProcess();
Test.stopTest();
System.assertEquals(0, Limits.getQueueableJobs(),
'No jobs should be enqueued for empty record list');
}
}
Testing the Full Domain Flow with Mock Bindings
When you want to test the full Criteria → Action pipeline without hitting the database, inject mock DomainProcessBinding__mdt records:
@IsTest
private class AccountDomainProcessTest {
@IsTest
static void onAfterUpdate_classifiesLargeAccountsAsStrategic() {
// Inject mock bindings — skips the metadata lookup. Match on
// Account / TriggerExecution / After_Update, sequence 10.
DomainProcessCoordinator.setMockDomainProcessBindings(
new List<DomainProcessBinding__mdt>{
new DomainProcessBinding__mdt(
Type__c = 'Criteria', ClassToInject__c = 'LargeAccountCriteria',
RelatedDomainBindingSObject__c = 'Account', ProcessContext__c = 'TriggerExecution',
TriggerOperation__c = 'After_Update', OrderOfExecution__c = 10.10, IsActive__c = true),
new DomainProcessBinding__mdt(
Type__c = 'Action', ClassToInject__c = 'MarkStrategicAccountAction',
RelatedDomainBindingSObject__c = 'Account', ProcessContext__c = 'TriggerExecution',
TriggerOperation__c = 'After_Update', OrderOfExecution__c = 10.20, IsActive__c = true)
});
// Build domain with test records and drive the coordinator directly
List<Account> accounts = new List<Account>{
new Account(Name = 'BigCo', AnnualRevenue = 5000000),
new Account(Name = 'SmallCo', AnnualRevenue = 200000)
};
AccountDomain domain = new AccountDomain(accounts);
new DomainProcessCoordinator(domain).processDomainLogicInjections(
DomainProcessConstants.PROCESS_CONTEXT.TriggerExecution,
System.TriggerOperation.After_Update);
// Only BigCo should be Strategic (before-context action mutates in place)
System.assertEquals('Strategic', accounts[0].Status__c);
System.assertEquals(null, accounts[1].Status__c);
}
}
Testing a Service with All Dependencies Mocked
Service tests verify orchestration logic — that the service calls the right things in the right order.
@IsTest
private class SalesAccountsServiceImplTest {
@IsTest
static void processAccountUpdates_loadsAccountsAndRunsDomainProcess() {
// Arrange
Id acct1Id = fflib_IDGenerator.generate(Account.SObjectType);
Id acct2Id = fflib_IDGenerator.generate(Account.SObjectType);
Set<Id> inputIds = new Set<Id>{ acct1Id, acct2Id };
List<Account> fakeAccounts = new List<Account>{
new Account(Id = acct1Id, Name = 'BigCo', AnnualRevenue = 5000000),
new Account(Id = acct2Id, Name = 'SmallCo', AnnualRevenue = 100000)
};
fflib_ApexMocks mocks = new fflib_ApexMocks();
// Mock selector
IAccountsSelector mockSel =
(IAccountsSelector) mocks.mock(IAccountsSelector.class);
// Mock UoW
IApplicationSObjectUnitOfWork mockUow =
(IApplicationSObjectUnitOfWork) mocks.mock(IApplicationSObjectUnitOfWork.class);
mocks.startStubbing();
mocks.when(mockSel.sObjectType()).thenReturn(Account.SObjectType);
mocks.when(mockSel.selectById(inputIds)).thenReturn(fakeAccounts);
mocks.stopStubbing();
Application.Selector.setMock(Account.SObjectType, mockSel);
Application.UnitOfWork.setMock(mockUow);
// Inject mock bindings
DomainProcessCoordinator.setMockDomainProcessBindings(new List<DomainProcessBinding__mdt>());
// Act — test the registered implementation directly
Test.startTest();
new SalesAccountsServiceImpl().processAccountUpdates(inputIds);
Test.stopTest();
// Verify selector was called
((IAccountsSelector) mocks.verify(mockSel, 1)).selectById(inputIds);
((IApplicationSObjectUnitOfWork) mocks.verify(mockUow, 1))
.register(fakeAccounts);
// Verify UoW was committed
((IApplicationSObjectUnitOfWork) mocks.verify(mockUow, 1)).commitWork();
}
@IsTest
static void processAccountUpdates_doesNothingForEmptyResult() {
fflib_ApexMocks mocks = new fflib_ApexMocks();
IAccountsSelector mockSel =
(IAccountsSelector) mocks.mock(IAccountsSelector.class);
IApplicationSObjectUnitOfWork mockUow =
(IApplicationSObjectUnitOfWork) mocks.mock(IApplicationSObjectUnitOfWork.class);
mocks.startStubbing();
mocks.when(mockSel.sObjectType()).thenReturn(Account.SObjectType);
mocks.when(mockSel.selectById(new Set<Id>()))
.thenReturn(new List<Account>());
mocks.stopStubbing();
Application.Selector.setMock(Account.SObjectType, mockSel);
Application.UnitOfWork.setMock(mockUow);
new SalesAccountsServiceImpl().processAccountUpdates(new Set<Id>());
// commitWork should not be called when there are no accounts
((IApplicationSObjectUnitOfWork) mocks.verify(mockUow, 0)).commitWork();
}
}
Integration Tests
Integration tests opt in to real database operations. Use them to verify the end-to-end trigger behavior, including the correct metadata being read.
@IsTest
private class SalesAccountIntegrationTest {
@IsTest
static void accountUpdate_triggersCorrectClassification() {
// Setup: insert real test data
List<Account> accounts = new List<Account>{
new Account(Name = 'BigCo', AnnualRevenue = 5000000, Status__c = 'Unknown'),
new Account(Name = 'SmallCo', AnnualRevenue = 100000, Status__c = 'Unknown')
};
insert accounts;
// Act: update triggers the domain
Test.startTest();
accounts[0].AnnualRevenue = 6000000; // still large
accounts[1].AnnualRevenue = 200000; // still small
update accounts;
Test.stopTest();
// Assert: verify final state
List<Account> updated = [SELECT Id, Name, Status__c FROM Account WHERE Id IN :accounts];
Map<String, String> statusByName = new Map<String, String>();
for (Account a : updated) {
statusByName.put(a.Name, a.Status__c);
}
System.assertEquals('Strategic', statusByName.get('BigCo'),
'BigCo should be classified as Strategic');
System.assertEquals('Standard', statusByName.get('SmallCo'),
'SmallCo should be classified as Standard');
}
@IsTest
static void accountSelector_includesInjectedSalesFields() {
Account acct = new Account(
Name = 'TestSales',
AnnualRevenue = 500000,
SalesStage__c = 'Prospecting'
);
insert acct;
// Query through the singular selector — fieldset injection includes SalesStage__c
List<Account> results = AccountsSelector.newInstance().selectById(
new Set<Id>{ acct.Id }
);
System.assertEquals(1, results.size());
// This assertion passes only if SelectorConfig_FieldSetInclusion__mdt is deployed
System.assertEquals('Prospecting', results[0].SalesStage__c,
'SalesStage__c should be returned via fieldset injection');
}
}
Integration tests are slower (they hit the database) and require real metadata deployments. Use them for:
- Verifying that your trigger fires and domain processes run correctly
- Confirming fieldset injection includes the expected fields
- End-to-end validation before a release
Test Organization Recommendations
One test class per production class: LargeAccountCriteriaTest, MarkStrategicAccountActionTest, SalesAccountsServiceImplTest.
Unit tests in the test class: Mock everything and test the class's logic in isolation.
Integration test as a separate class: SalesAccountIntegrationTest — touches the database, runs against real metadata, validates the full stack.
Test method naming: methodUnderTest_condition_expectedBehavior
// Good
largeAccountCriteria_run_returnsOnlyAccountsAboveThreshold()
processAccountUpdates_whenEmpty_doesNotCommitUow()
// Avoid
testLargeAccount()
test1()
Mock Setup Cheat Sheet
// Mock a Selector — stub sObjectType(); setMock() asks the mock for it
fflib_ApexMocks mocks = new fflib_ApexMocks();
IAccountsSelector mockSel =
(IAccountsSelector) mocks.mock(IAccountsSelector.class);
mocks.startStubbing();
mocks.when(mockSel.sObjectType()).thenReturn(Account.SObjectType);
mocks.when(mockSel.selectById(accountIds)).thenReturn(fakeAccounts);
mocks.stopStubbing();
Application.Selector.setMock(Account.SObjectType, mockSel);
// Mock a Domain
IApplicationSObjectDomain mockDomain =
(IApplicationSObjectDomain) mocks.mock(AccountDomain.class);
Application.Domain.setMock(mockDomain);
// Mock a Service (the interface; register it for the impl's binding key)
ISalesAccountsService mockSvc =
(ISalesAccountsService) mocks.mock(ISalesAccountsService.class);
Application.Service.setMock(ISalesAccountsService.class, mockSvc);
// Mock a UnitOfWork
IApplicationSObjectUnitOfWork mockUow =
(IApplicationSObjectUnitOfWork) mocks.mock(IApplicationSObjectUnitOfWork.class);
Application.UnitOfWork.setMock(mockUow);
// Mock DomainProcessBindings
DomainProcessCoordinator.setMockDomainProcessBindings(bindingList);
// Verify a call was made
((IApplicationSObjectUnitOfWork) mocks.verify(mockUow, 1))
.register(expectedAccounts);
// Verify a call was never made
((ISalesAccountsService) mocks.verify(mockSvc, 0))
.processAccountUpdates(fflib_Match.anyObject());
Next Steps
Use the Reference page as a quick lookup for metadata types, key classes, and common errors during day-to-day development.