//_blog

Brewtiful Beans Learns AT4DX, Part 9: Tasting Notes

Suppose a large account keeps its old status after an update. Joe could step through the trigger, but the revenue rule, the action, and the binding are all suspects. He starts with a focused test for each, then checks the full path.

After this post, you can:

  • Test a rule and a service without relying on the database.
  • Use mock bindings to check a domain process.
  • Choose an integration test when deployed wiring matters.

Why Each Layer Is Testable

Every AT4DX dependency sits behind a factory. In production, the factory reads metadata and returns the real class. In tests, you tell the factory to return a mock instead:

Application.Selector.setMock(Account.SObjectType, mockSelector);
Application.Domain.setMock(mockDomain);
Application.Service.setMock(ISalesAccountsService.class, mockService);
Application.UnitOfWork.setMock(mockUow);

Any combination of those can be set before the code under test runs. The factory hands back the mock, so the test never reads metadata and never runs a query. That gives you three properties:

  • Unit tests run in memory. No DML, no SOQL, no metadata reads.
  • Each class gets its own focused test. Criteria, actions, services, and domains are tested separately.
  • Integration tests opt in. Leave the mocks unset, and the code runs against the real stack.

Typing Tax: Mocks are the most boilerplate-heavy part of this series. Each mocks.startStubbing() / stopStubbing() block is about six lines before you’ve asserted anything. The payoff is that a service test runs in milliseconds and doesn’t need a seeded org, and the first time it catches a broken orchestration step, you’ll stop grumbling.

Testing a Criteria: No Mocks Needed

A Criteria is a pure function. Records go in, a filtered list comes out. There’s nothing to mock, so the test is short:

@IsTest
private class LargeAccountCriteriaTest {
    @IsTest
    static void largeAccountCriteria_run_returnsOnlyAccountsAboveThreshold() {
        List<SObject> input = new List<SObject>{
            new Account(Name = 'HugeCo',  AnnualRevenue = 5000000),
            new Account(Name = 'MidCo',   AnnualRevenue = 1000000), // exactly 1M is 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 largeAccountCriteria_run_handlesNullAnnualRevenue() {
        List<SObject> input = new List<SObject>{
            new Account(Name = 'NullCo', AnnualRevenue = null)
        };

        LargeAccountCriteria criteria = new LargeAccountCriteria();
        criteria.setRecordsToEvaluate(input);

        System.assert(criteria.run().isEmpty(), 'Null revenue should not match');
    }
}

Notice the boundary case. MidCo sits at exactly one million, and the test pins down that it’s not large. Boundary values are where rules break, so they belong in the test. The null case matters for the same reason.

Testing a Sync Action: Drive It the Way the Coordinator Does

An action is tested the same way the coordinator drives it: hand it records with setRecordsToActOn(...), call runInProcess(), and inspect the result. MarkStrategicAccountAction runs in before-trigger context and mutates records in place, so it doesn’t need a Unit of Work.

@IsTest
private class MarkStrategicAccountActionTest {
    @IsTest
    static void markStrategicAccountAction_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 markStrategicAccountAction_runInProcess_handlesEmptyRecordList() {
        MarkStrategicAccountAction action = new MarkStrategicAccountAction();
        action.setRecordsToActOn(new List<SObject>());

        action.runInProcess(); // should be a no-op without throwing
    }
}

fflib_IDGenerator.generate(Account.SObjectType) gives the test a fake, well-formed Id. Use it whenever the code needs an Id but nothing will insert the record, so you don’t have to fake the Id by hand.

If an action stages DML against other records, it needs a Unit of Work. Inject a mock with action.setUnitOfWork(mockUow), run the action, and verify the register(...) call. That’s the same verification pattern as the service test below.

Testing an Async Action

An async action doesn’t do its work. It enqueues a job. The test checks that the job got queued:

@IsTest
private class NotifyExternalSystemActionTest {
    @IsTest
    static void notifyExternalSystemAction_runInProcess_enqueuesJobForLargeAccounts() {
        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();
        // Limits.getQueueableJobs() counts jobs queued in this transaction,
        // so check it before stopTest() runs the queue.
        System.assertEquals(1, Limits.getQueueableJobs(),
            'One queueable should be enqueued');
        Test.stopTest();
    }

    @IsTest
    static void notifyExternalSystemAction_runInProcess_doesNotEnqueueForEmptyList() {
        NotifyExternalSystemAction action = new NotifyExternalSystemAction();
        action.setRecordsToActOn(new List<SObject>());

        Test.startTest();
        action.runInProcess();
        System.assertEquals(0, Limits.getQueueableJobs(),
            'No job should be enqueued for an empty list');
        Test.stopTest();
    }
}

The queueable’s callout is a separate concern, and it gets its own test. This one checks only that the action made the right decision to enqueue.

Testing the Pipeline with Mock Bindings

Sometimes you want to test the whole Criteria-to-Action chain without a metadata lookup. Inject bindings with setMockDomainProcessBindings, then drive the coordinator directly.

The binding’s TriggerOperation__c has to match the operation the test drives. The coordinator runs only the bindings that match the context and the operation, so a mismatch means nothing runs, and the assertions fail for a reason that’s hard to spot.

@IsTest
private class AccountDomainProcessTest {
    @IsTest
    static void accountDomain_processDomainLogic_classifiesLargeAccountsAsStrategic() {
        // Match the operation you drive below: Before_Update.
        // The action mutates Status__c in place, so it has to run before the save.
        DomainProcessCoordinator.setMockDomainProcessBindings(
            new List<DomainProcessBinding__mdt>{
                new DomainProcessBinding__mdt(
                    Type__c = 'Criteria', ClassToInject__c = 'LargeAccountCriteria',
                    RelatedDomainBindingSObject__c = 'Account',
                    ProcessContext__c = 'TriggerExecution',
                    TriggerOperation__c = 'Before_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 = 'Before_Update',
                    OrderOfExecution__c = 10.20, IsActive__c = true)
            });

        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.Before_Update);

        System.assertEquals('Strategic', accounts[0].Status__c);
        System.assertEquals(null,        accounts[1].Status__c);
    }
}

This test is about the coordinator’s wiring, not the rule itself. The rule is already tested on its own, so here you check that the sequence picks the right records and the action runs in order.

Testing a Service with Everything Mocked

A service test checks orchestration: it asks the right collaborator for data, calls the right unit-of-work methods, and does nothing when there’s nothing to do. Here’s SalesAccountsServiceImpl.processAccountUpdates, with the selector and the Unit of Work both mocked:

@IsTest
private class SalesAccountsServiceImplTest {
    @IsTest
    static void processAccountUpdates_whenAccountsFound_registersAndCommits() {
        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();
        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(inputIds)).thenReturn(fakeAccounts);
        mocks.stopStubbing();

        Application.Selector.setMock(Account.SObjectType, mockSel);
        Application.UnitOfWork.setMock(mockUow);

        new SalesAccountsServiceImpl().processAccountUpdates(inputIds);

        ((IAccountsSelector) mocks.verify(mockSel, 1)).selectById(inputIds);
        ((IApplicationSObjectUnitOfWork) mocks.verify(mockUow, 1)).register(fakeAccounts);
        ((IApplicationSObjectUnitOfWork) mocks.verify(mockUow, 1)).commitWork();
    }

    @IsTest
    static void processAccountUpdates_whenNoAccountsFound_doesNotCommit() {
        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>());

        ((IApplicationSObjectUnitOfWork) mocks.verify(mockUow, 0)).commitWork();
    }
}

Two things to notice. First, the stubbing of sObjectType() isn’t optional. Application.Selector.setMock asks the mock which SObject it serves, so an unstubbed mock fails at setup. Second, the verify calls check what happened. The test doesn’t care how the service got there, only that it asked for the accounts, registered them, and committed.

Joe’s isolated tests pass, but that still does not prove the bindings and fieldset made it into the org. A test that supplies its own mocks cannot answer that.

Integration Tests: Taste the Blend

Integration tests skip the mocks and run the real stack: real metadata, real triggers, real database. They’re slower, and they only pass in an org where the metadata is deployed.

@IsTest
private class SalesAccountIntegrationTest {
    @IsTest
    static void accountUpdate_classifiesLargeAndSmallAccounts() {
        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;

        Test.startTest();
        accounts[0].AnnualRevenue = 6000000; // still large
        accounts[1].AnnualRevenue = 200000;  // still small
        update accounts;
        Test.stopTest();

        Map<String, String> statusByName = new Map<String, String>();
        for (Account acct : [SELECT Name, Status__c FROM Account WHERE Id IN :accounts]) {
            statusByName.put(acct.Name, acct.Status__c);
        }

        System.assertEquals('Strategic', statusByName.get('BigCo'));
        System.assertEquals('Standard',  statusByName.get('SmallCo'));
    }

    @IsTest
    static void accountSelector_includesInjectedSalesFields() {
        Account acct = new Account(Name = 'TestSales', AnnualRevenue = 500000,
                                   SalesStage__c = 'Prospecting');
        insert acct;

        List<Account> results = AccountsSelector.newInstance().selectById(
            new Set<Id>{ acct.Id });

        System.assertEquals(1, results.size());
        // Passes only if SelectorConfig_FieldSetInclusion__mdt is deployed.
        System.assertEquals('Prospecting', results[0].SalesStage__c);
    }
}

The first test is the one that proves the whole chain works. It checks that the trigger fires, the domain runs, and the metadata bindings are read. The second proves fieldset injection from Part 5 is live.

Keep the integration layer small. Each integration test is slow, and each one depends on deployed metadata. Use them for:

  • Confirming the trigger fires and the domain processes run.
  • Confirming fieldset injection includes the expected fields.
  • Smoke-testing the release before it ships.

Everything else belongs in a unit test.

Organizing the Tests

  • One test class per production class. LargeAccountCriteriaTest, MarkStrategicAccountActionTest, SalesAccountsServiceImplTest.
  • Unit tests in the class. Mock everything and test the class’s own logic.
  • Integration tests in their own class. SalesAccountIntegrationTest touches the database and runs against real metadata.
  • Name methods unitOrClass_method_expectedBehavior. For example, largeAccountCriteria_run_returnsOnlyAccountsAboveThreshold or processAccountUpdates_whenNoAccountsFound_doesNotCommit. A failing test name should tell you what broke without opening the file.

Mock Cheat Sheet

// Mock a selector: stub sObjectType(), because 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 service: key it on the interface, the same type the factory asks for
ISalesAccountsService mockSvc =
    (ISalesAccountsService) mocks.mock(ISalesAccountsService.class);
Application.Service.setMock(ISalesAccountsService.class, mockSvc);

// Mock a unit of work
IApplicationSObjectUnitOfWork mockUow =
    (IApplicationSObjectUnitOfWork) mocks.mock(IApplicationSObjectUnitOfWork.class);
Application.UnitOfWork.setMock(mockUow);

// Inject domain process bindings in place of metadata
DomainProcessCoordinator.setMockDomainProcessBindings(bindingList);

// Verify a call happened
((IApplicationSObjectUnitOfWork) mocks.verify(mockUow, 1)).register(expectedAccounts);

// Verify a call never happened
((ISalesAccountsService) mocks.verify(mockSvc, 0))
    .processAccountUpdates(fflib_Match.anyObject());

Check Your Brew

1. Why does a Criteria test need no mocks?

  • A. Criteria classes are exempt from the factory
  • B. The fflib_ApexMocks library is only for Actions
  • C. A Criteria is a pure function from records to a filtered list, with no collaborators to replace
  • D. Criteria run only in integration tests
Reveal the answer

C. A Criteria takes records in and returns records out. It doesn’t call a selector, a service, or a Unit of Work, so there’s nothing to replace.

2. Your domain-pipeline test asserts that Status__c was set, but the assertion fails and nothing seems to run. What’s the most likely cause?

  • A. Status__c isn’t a valid field
  • B. The binding’s TriggerOperation__c doesn’t match the operation the test drives, so the coordinator skips the bindings
  • C. Mock bindings can’t set fields
  • D. The coordinator only runs in integration tests
Reveal the answer

B. The coordinator runs only bindings that match the context and the operation. If the binding says After_Update and the test drives Before_Update, nothing matches, so nothing runs.

3. Why must a mocked selector stub sObjectType() before Application.Selector.setMock is called?

  • A. Without it, the test won’t compile
  • B. It disables the factory for the rest of the test
  • C. It makes the mock run faster
  • D. setMock asks the mock which SObject it serves, so an unstubbed mock fails at setup
Reveal the answer

D. Application.Selector.setMock registers the mock under the SObject it reports. Stub sObjectType() so that call has an answer.

Next up: Part 10, You Did It! We’ll look back over the whole trail, and then we’ll talk about the one command that generates most of what you just typed by hand.