Mocks let you isolate the unit under test from real dependencies. Beyond the well-known HttpCalloutMock, here are common scenarios:
1. Mock SOQL via dependency injection:
`apex public interface IAccountSelector { List<Account> selectByIds(Set<Id> ids); }
public class AccountSelector implements IAccountSelector { public List<Account> selectByIds(Set<Id> ids) { return [SELECT Id FROM Account WHERE Id IN :ids]; } }
// In test: public class MockAccountSelector implements IAccountSelector { public List<Account> selectByIds(Set<Id> ids) { return new List<Account>{ new Account(Id=ids.iterator().next(), Name='Mock') }; } }
// Test injects MockAccountSelector `
The service class accepts IAccountSelector in its constructor. Test passes the mock; production passes the real one.
2. Mock external service via Stub API:
`apex public class MockStripeApi implements System.StubProvider { public Object handleMethodCall(Object stub, String name, Type returnType, List<Type> paramTypes, List<String> paramNames, List<Object> args) { if (name == 'charge') return 'ch_mock_123'; return null; } }
@isTest static void testCharge() { StripeApi mocked = (StripeApi) Test.createStub(StripeApi.class, new MockStripeApi()); // mocked.charge() returns 'ch_mock_123' instead of hitting real Stripe } `
Test.createStub is Salesforce's built-in mocking framework. Works on virtual / interface-based dependencies.
3. Mock Custom Metadata / Custom Settings:
In tests, build the custom type record directly:
apex Region_Tax__mdt rate = new Region_Tax__mdt(DeveloperName='US', Rate__c=0.075); // Inject into the service that would normally call .getInstance()
For Custom Settings, just insert test rows in @TestSetup.
4. Mock async work via flushing:
Test.startTest() ... Test.stopTest() runs queued async synchronously. Tests can mock the result by checking final state.
5. Mock current time:
Apex doesn't natively support DateTime.now() mocking. Pattern: wrap in a service.
apex public virtual class TimeService { public virtual DateTime getNow() { return DateTime.now(); } }
Test injects a TimeService subclass returning fixed time.
6. fflib_ApexMocks — sophisticated open-source mocking library. Verify call counts, argument matchers, sequence checks.
Anti-pattern: testing without mocks at all. Tests then depend on real services, become slow, flaky, and fragile.
Senior Apex code is designed for testability — every external dependency goes through an interface so it can be mocked.
