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 {        
    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

global class ExampleCalloutMock implements HttpCalloutMock{
    global HttpResponse respond(HTTPRequest req){
        HttpResponse res = new HttpResponse();
        res.setBody('GREAT SCOTT');
        return res;

2 . Create actual Test Class for your Apex Class

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.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

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


Phanindra Mangipudi

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