function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mohammad Alazzouni 16Mohammad Alazzouni 16 

How to write a test class for an Async Request?

Hi,

I am having difficulty writing a test class for an apex class that doesn't invoke any changes in Salesforce. Instead, it invokes changes to an external system. I don't even know where to begin with this test class. I figured it would help if I give you the code:
 
global class AsyncRequest {

    //@HttpPost
    @future (callout=true)
    global static void postRequest(string contactJSON, 
                                  string flAdminUser, 
                                  string flUserId,
                                  string sfUserId){
                Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://dev-api-example.com/api/v2.5/integrations/salesforce/profile');
        request.setMethod('POST');
        //request.setHeader('FL-SECRET', 'Example.secret');
        request.setHeader('FL-SECRET', 'SF2018/Example');
        request.setHeader('FL-ADMIN-USER', flAdminUser);
        request.setHeader('Content-Type', 'application/json');
        request.setHeader('FL-USER-ID', flUserId);
        request.setHeader('SF-USER-ID', sfUserId);
        // Set the body as a JSON object
        request.setBody(contactJSON);
        HttpResponse response = http.send(request);
        // Parse the JSON response
        if (response.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
            System.debug(response.getBody());
        }
            
    }
}

Then here is another .apext file that I would need to test as well
 
trigger AsyncToFarmLead on Contact (after update) {
    
    String FlAdminUser;
    String contactJSON;
    String FlUserId;
    String SfUserId;
    
    for(Contact a : Trigger.New) {
        
        Map<String,Object> conMap = (Map<String,Object>)JSON.deserializeUntyped(JSON.serialize(a));
        
        removeAttributes(conMap, 'Account');
        removeAttributes(conMap, 'FL_ADMIN_USER__c');
        removeAttributes(conMap, 'FarmLead_URL__c');
        removeAttributes(conMap, 'AccountId');
        removeAttributes(conMap, 'FarmLead_Secret_key__c');
        
        String contactJSON = (JSON.serializePretty(conMap));
        
        if(a.FL_ADMIN_USER__c != null) {
            FlAdminUser = a.FL_ADMIN_USER__c;
        } else {
            FlAdminUser = 'nullVal';
        }
        System.debug('FL_ADMIN_USER__c: ' + FlAdminUser);
        
        if(a.MK_fl_user_id__c != null) {
            FlUserId = a.MK_fl_user_id__c;
        } else {
            FlUserId = 'nullVal';
        }
        System.debug('MK_fl_user_id__c: ' + FlUserId);
        
        if(a.Id != null) {
            SfUserId = a.Id;
        } else {
            SfUserId = 'nullVal';
        }
        System.debug('Id: ' + SfUserId);

        try{
            System.debug('JSON being passed: ' + contactJSON);
            AsyncRequest.postRequest(contactJSON, FlAdminUser, FlUserId, SfUserId);
        } catch (Exception e) {
             Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
             String[] toAddresses = new String[] {'EXAMPLE@Email.com'};
             mail.setToAddresses(toAddresses);
             mail.setReplyTo('EXAMPLE@Email.com');
             mail.setSenderDisplayName('Apex error message');
             mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
             mail.setPlainTextBody(e.getMessage());
             Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }
    
    private void removeAttributes(Map<String,Object> jsonObj, String attribute)  {
        for(String key : jsonObj.keySet()) {
            if(key == attribute) {
                jsonObj.remove(key);
            } else {
                if(jsonObj.get(key) instanceof Map<String,Object>) {
                    removeAttributes((Map<String,Object>)jsonObj.get(key), attribute);
                }
                if(jsonObj.get(key) instanceof List<Object>) {
                    for(Object listItem : (List<Object>)jsonObj.get(key)) {
                        if(listItem instanceof Map<String,Object>)  {
                            removeAttributes((Map<String,Object>)listItem, attribute);
                        }
                    }
                }
            }
        }  
    }
}

 
Best Answer chosen by Mohammad Alazzouni 16
SFDC RohitSFDC Rohit
MockResponse class:-
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
   // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('http://google.com', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
  
       // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"access_token":"8UT28QKGORMivFqne-6PMRLdTYk3AS0mcxdVwRJEwYsTjwZjqGopk1TRzGX7vHSZpFNFL3HOmX3RKZrQkBap3b16j-XVkwArdDbhusArOBGzYsD1cpA8B87N_RedJrd9btvq2i22cAjPvyJLSVMc297U0V9YZ9rJ3tM429G8mglnsUNUVJJi_nnTJAN6-H038B4Y1aQeRQZVdU72Nr942eYZ3fXv1HXfxwYUZgWyYO5juVaVnoq_ZJHcrFGXfNp5LVrNlnEibHhJ2RGeD-MYKhyVjfkTrATGQhYY--OVCOemUyWKTlwgwBFjgzfpQfOq79raEglOTgEF3Qx78RY2-nBNvgOTRMET4B2fT17Q8EN4UCQLxGZTGq1ACN5j2B3YKT7isjzwAgysloYGJsL4j4D8dCGKgWBO0rTXwx7MfkNsX5TjAYRNCip5vTSRXeSBqhjM_TtwbKCA0HexikSz-XryZT7pKGYhjfRCXtWudd7OUjFYoDRfKTiAhjNk5yJj","token_type":"bearer","expires_in":86400,"userName":"test@gmail.com",".issued":"Thu, 25 Jun 2015 12:56:23 GMT",".expires":"Fri, 26 Jun 2015 12:56:23 GMT"}');
        res.setStatusCode(200);
        return res;
    }
}

Test Class getting fake response  from the class MockHttpResponseGenerator that implements HttpCalloutMock
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
       // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());  
       // Call method to test.
        // This causes a fake response to be sent from the class that implements HttpCalloutMock.
        PageReference pageRef = new WebserviceCall().getaccesstoken();
    }
}

All Answers

Manj_SFDCManj_SFDC
you need to invoke a mock asynchronous callout in a test for a Web service call , please refer this
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_continuation_testing.htm
Good luck !
SFDC RohitSFDC Rohit
MockResponse class:-
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
   // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('http://google.com', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
  
       // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"access_token":"8UT28QKGORMivFqne-6PMRLdTYk3AS0mcxdVwRJEwYsTjwZjqGopk1TRzGX7vHSZpFNFL3HOmX3RKZrQkBap3b16j-XVkwArdDbhusArOBGzYsD1cpA8B87N_RedJrd9btvq2i22cAjPvyJLSVMc297U0V9YZ9rJ3tM429G8mglnsUNUVJJi_nnTJAN6-H038B4Y1aQeRQZVdU72Nr942eYZ3fXv1HXfxwYUZgWyYO5juVaVnoq_ZJHcrFGXfNp5LVrNlnEibHhJ2RGeD-MYKhyVjfkTrATGQhYY--OVCOemUyWKTlwgwBFjgzfpQfOq79raEglOTgEF3Qx78RY2-nBNvgOTRMET4B2fT17Q8EN4UCQLxGZTGq1ACN5j2B3YKT7isjzwAgysloYGJsL4j4D8dCGKgWBO0rTXwx7MfkNsX5TjAYRNCip5vTSRXeSBqhjM_TtwbKCA0HexikSz-XryZT7pKGYhjfRCXtWudd7OUjFYoDRfKTiAhjNk5yJj","token_type":"bearer","expires_in":86400,"userName":"test@gmail.com",".issued":"Thu, 25 Jun 2015 12:56:23 GMT",".expires":"Fri, 26 Jun 2015 12:56:23 GMT"}');
        res.setStatusCode(200);
        return res;
    }
}

Test Class getting fake response  from the class MockHttpResponseGenerator that implements HttpCalloutMock
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
       // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());  
       // Call method to test.
        // This causes a fake response to be sent from the class that implements HttpCalloutMock.
        PageReference pageRef = new WebserviceCall().getaccesstoken();
    }
}
This was selected as the best answer
Manj_SFDCManj_SFDC
Mark this as solved if this helps you, you too will fetch some points if the question is marked as solved :)
https://developer.salesforce.com/forums#!/feedtype=SINGLE_QUESTION_DETAIL&dc=Developer_Forums&criteria=ALLQUESTIONS&id=9060G000000MVrtQAG