Salesforce Developer Future Methods Testing


// Salesforce - Developer - Future Methods - Testing:

Testing future methods is a little different than typical Apex testing. To test 
future methods, enclose your test code between the startTest and stopTest test 
methods. The system collects all asynchronous calls made after the startTest. 
When stopTest is executed, all these collected asynchronous processes are then 
run synchronously. You can then assert that the asynchronous call operated 

Test code cannot actually send callouts to external systems, so you’ll have 
to ‘mock’ the callout for test coverage. 

Here’s our mock callout class used for testing. The Apex testing framework 
utilizes this ‘mock’ response instead of making the actual callout to the REST 
API endpoint.

global class SMSCalloutMock implements HttpCalloutMock {
    global HttpResponse respond(HttpRequest req) {
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        return res; 

The test class contains a single test method, which tests both the asynchronous 
and synchronous methods as the former calls the latter.

private class Test_SMSUtils {
  private static void testSendSms() {
    Test.setMock(HttpCalloutMock.class, new SMSCalloutMock());
      SMSUtils.sendSMSAsync('111', '222', 'Greetings!');
    // runs callout and check results
    List<SMS_Log__c> logs = [select msg__c from SMS_Log__c];
    System.assertEquals(1, logs.size());
    System.assertEquals('success', logs[0].msg__c);
// Salesforce - Developer - Future Methods - Testing:

public class AccountProcessor {
    public static void countContacts(List<String> ids) {
        for (Account[] accounts : [SELECT Name, (SELECT LastName FROM Contacts) Conta FROM Account WHERE Id = :ids]) {
            for (Account a : accounts) {
                System.debug(a.Id + ', ' + + ', Contacts:' + a.contacts.size());
                a.Number_of_Contacts__c = a.contacts.size();
            update accounts;

public class AccountProcessorTest {
    public static testmethod void test1() {
        Account a1 = new Account(Name = 'KhaiTest');
        insert a1;
        Contact c1 = new Contact(FirstName = 'KhaiTest', LastName = 'KhaiTest');
        c1.AccountId = a1.Id;
        insert c1;

        List<String> t = new List<String>();
        Account a2 = [SELECT Number_of_Contacts__c FROM Account WHERE id = :a1.Id];
        System.assertEquals(1, a2.Number_of_Contacts__c);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License