Test Classes For Future Methods (Callout True)

Apex Sep 24, 2014

Wondering how to write Test class for Apex Classes/Methods which has Callout=true, here we go

Actual Class

public class exampleClass {        
    @future(callout=true)
    public static void sampleMethod(String param){
         ......Code goes here........
    }
}

Create a global Test Class

1 . Create a global test class which implements HttpCalloutMock as shown, this is like helper test class which will used in acutal Test class

@isTest
global class ExampleCalloutMock implements HttpCalloutMock{
    global HttpResponse respond(HTTPRequest req){
        HttpResponse res = new HttpResponse();
        res.setStatus('OK');
        res.setStatusCode(200);
        res.setBody('GREAT SCOTT');
        return res;
    }
}

2 . Create actual Test Class for your Apex Class

@isTest
private class exampleClass_Test {    
    static Account getTestAccount(){
        Account myAcc = new Account(Name = 'Test');
        insert myAcc;
        return myAcc;
    }
    
    private static testMethod void callFutureMethod() {        
        Account a = getTestAccount();
        
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new ExampleCalloutMock());
        exampleClass.sampleMethod(a.Id, 'Test Text using future Call out', userinfo.getUserId(), userinfo.getSessionId());    
        // exampleClass is which we created in STEP 1, and invoking its method
        Test.stopTest();
        
    }
}

That's it invoke your webservice/callout methods under Test.startTest(); & Test.stopTest();, in between use Test.setMock(HttpCalloutMock.class, new ExampleCalloutMock()); followed your method

Need any help please comment below

Thanks,

Phanindra Mangipudi

Salesforce, Lightning Web Componets, Node.Js, Angular 2+, Bootstrap