In Apex, we developers are basically wizards, but even wizards need to fake a few spells once in a while. That’s where mocking comes in! Whether you’re pretending to call an external API (because who wants to actually wait for a real response?), faking a batch job (because no one has time for processing millions of records in a test), or just making Salesforce think it scheduled a job (shhh, don’t tell it), we’ve got you covered.

Below are the most commonly used mocking interfaces in Apex, along with examples to make your test classes as magically convincing as possible. Let’s go!”

1. HttpCalloutMock (Mock HTTP Callouts)

Used to mock an external HTTP request/response in test methods.

Example:

@isTest
public class AccountCalloutMock implements HttpCalloutMock {
    public HTTPResponse respond(HTTPRequest req) {
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"success": true, "message": "Mock response"}');
        res.setStatusCode(200);
        return res;
    }
}

Usage in a Test Class:

@isTest
public class AccountCalloutTest {
    @isTest
    static void testHttpCallout() {
        Test.setMock(HttpCalloutMock.class, new AccountCalloutMock());
        
        // Call your method that makes an HTTP callout here
        String response = MyClass.makeHttpCallout();
        
        System.assertEquals('Mock response', response);
    }
}

2. QueueableMock (Mock System.enqueueJob)

Used for mocking asynchronous Queueable Apex.

Example:

@isTest
public class QueueableJobMock implements Queueable, TestMock {
    public void execute(QueueableContext context) {
        System.debug('Queueable Job Executed in Test');
    }
}

Usage in a Test Class:

@isTest
public class QueueableTest {
    @isTest
    static void testQueueableJob() {
        Test.setMock(TestMock.class, new QueueableJobMock());
        
        System.enqueueJob(new QueueableJobMock());
        Test.startTest();
        Test.stopTest();
        
        System.assert(true);
    }
}

3. Database.Batchable<SObject> (Mock Batch Apex)

Used for mocking batch jobs.

Example:

@isTest
public class BatchJobMock implements Database.Batchable<SObject>, TestMock {
    public Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([SELECT Id FROM Account LIMIT 10]);
    }
    
    public void execute(Database.BatchableContext BC, List<SObject> scope) {
        System.debug('Mock batch executed with ' + scope.size() + ' records.');
    }
    
    public void finish(Database.BatchableContext BC) {
        System.debug('Mock batch job finished.');
    }
}

Usage in a Test Class:

@isTest
public class BatchJobTest {
    @isTest
    static void testBatchJob() {
        Test.setMock(TestMock.class, new BatchJobMock());
        
        Test.startTest();
        Database.executeBatch(new BatchJobMock(), 10);
        Test.stopTest();
        
        System.assert(true);
    }
}

4. Schedulable (Mock Scheduled Apex)

Used for mocking scheduled jobs.

Example:

@isTest
public class ScheduledJobMock implements Schedulable {
    public void execute(SchedulableContext SC) {
        System.debug('Mock scheduled job executed.');
    }
}

Usage in a Test Class:

@isTest
public class ScheduledJobTest {
    @isTest
    static void testScheduledJob() {
        String jobId = System.schedule('Test Job', '0 0 12 * * ?', new ScheduledJobMock());
        System.assertNotEquals(null, jobId);
    }
}

5. ExceptionMock (Mock Exception Handling)

Used to simulate exceptions in test cases.

Example:

@isTest
public class ExceptionMock implements HttpCalloutMock {
    public HTTPResponse respond(HTTPRequest req) {
        throw new CalloutException('Mocked Exception');
    }
}

Usage in a Test Class:

@isTest
public class ExceptionMockTest {
    @isTest
    static void testExceptionHandling() {
        Test.setMock(HttpCalloutMock.class, new ExceptionMock());
        
        try {
            MyClass.makeHttpCallout();
            System.assert(false, 'Expected exception not thrown');
        } catch (CalloutException e) {
            System.assertEquals('Mocked Exception', e.getMessage());
        }
    }
}

6. StubProvider (Advanced Apex Mocks)

Used for dependency injection and creating dynamic mocks.

Example:

public class MyStubProvider implements System.StubProvider {
    public Object handleMethodCall(Object obj, String methodName, 
                                   Type returnType, List<Type> paramTypes, 
                                   List<Object> paramValues) {
        if (methodName == 'getData') {
            return 'Mocked Data';
        }
        return null;
    }
}

Usage in a Test Class:

@isTest
public class StubProviderTest {
    @isTest
    static void testStub() {
        MyInterface mockObject = (MyInterface) System.Test.createStub(MyInterface.class, new MyStubProvider());
        String result = mockObject.getData();
        System.assertEquals('Mocked Data', result);
    }
}

Happy mocking….

Leave a comment