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
Developer.mikie.Apex.StudentDeveloper.mikie.Apex.Student 

HTTP Post Callout Method - Please help with Test - Currently gives 0% coverage

Hi Guys,

I cant figure out how to pass my integration class. Please help, any help would be much appreciated.

 

public class Integration {

    // The ExternalOrder class holds a string and integer
    // received from the external fulfillment system.

    public class ExternalOrder {
        public String id {
            get;
            set;
        }
        public String result {
            get;
            set;
        }
    }

    //  Functionally, the method 1) prepares
    // JSON-formatted data to send to the remote service, 2) makes an HTTP call
    // to send the prepared data to the remote service, and then 3) processes
    // any JSON-formatted data returned by the remote service to update the
    // local Invoices with the corresponding external IDs in the remote system.

    @future(callout = true) // indicates that this is an asynchronous call
    public static void postOrder(List < Id > AccountIds, boolean isScheduleExpiry) {

        //Call Accounts associated to Id List
        List < Account > Accounts = [SELECT Id, DestinyLive_Email_Username__c, Support_Expiration__c, Receiving_Support__c, DestinyLive_Premium_Membership_Expiry__c FROM Account WHERE Id IN: AccountIds];
        
        // Create a JSON generator object
        JSONGenerator gen = JSON.createGenerator(true);
        // open the JSON generator
        gen.writeStartArray();
        // iterate through the list of invoices passed in to the call
        // writing each Account ID to the array
        for (Account Acc: Accounts) {
        Datetime ExpiryDate = Acc.DestinyLive_Premium_Membership_Expiry__c;
        String myDatetimeStr = ExpiryDate.format('dd/MM/YYYY');
            gen.writeStartObject();
            gen.writeStringField('id', Acc.Id);
            if(Acc.DestinyLive_Email_Username__c != null && Acc.DestinyLive_Email_Username__c != ''){
            gen.writeStringField('DestinyLive_UserName', Acc.DestinyLive_Email_Username__c);
            }else{
            gen.writeStringField('DestinyLive_UserName', 'NA');
            }
            
            //Set Destiny Client to false as isScheduleExpiry == true because the class is scheduled to run 15 minutes before expiry
            if(isScheduleExpiry == true){
            gen.writeBooleanField('DestinyClient', false);
            }else{
            gen.writeBooleanField('DestinyClient', Acc.Receiving_Support__c);
            }
            gen.writeStringField('Expiry', myDatetimeStr);
            gen.writeEndObject();
        }
        // close the JSON generator
        gen.writeEndArray();
        // create a string from the JSON generator
        String jsonOrders = gen.getAsString();
        // debugging call, which you can check in debug logs
        System.debug('jsonOrders: ' + jsonOrders);

        // create an HTTPrequest object    
        HttpRequest req = new HttpRequest();
        // set up the HTTP request with a method, endpoint, header, and body
        req.setMethod('POST');
        // DON'T FORGET TO UPDATE THE FOLLOWING LINE WITH YOUR APP NAME
        req.setEndpoint('http://requestb.in/1n6j75u1');
        req.setHeader('Content-Type', 'application/json');
        req.setBody(jsonOrders);
        // create a new HTTP object
        Http http = new Http();
        // create a new HTTP response for receiving the remote response
        // then use it to send the configured HTTPrequest
        HTTPResponse res = http.send(req);
        // debugging call, which you can check in debug logs
        System.debug('Fulfillment service returned ' + res.getBody());

        // 3) see above

        // Examine the status code from the HTTPResponse
        // If status code != 200, write debugging information, done
        if (res.getStatusCode() != 200) {
            System.debug('Error from ' + req.getEndpoint() + ' : ' + res.getStatusCode() + ' ' + res.getStatus());
        }
        // If status code = 200, update each Account
        // with the external ID returned by the fulfillment service.
        else {

            // Create a list of external orders by deserializing the
            // JSON data returned by the fulfillment service.
            List < ExternalOrder > orders = (List < ExternalOrder > ) JSON.deserialize(res.getBody(),
            List < ExternalOrder > .class);
            // Create a map of Invoice IDs from the retrieved
            Map < Id, Account > AccMap = new Map < Id, Account > (Accounts);
            // Update the order numbers in the invoices
            for (ExternalOrder order: orders) {
            
            if(order.result == 'Success'){
                Account Acc = AccMap.get(order.id);
                Acc.DestinyLive_Premium_Membership__c= False;
                Acc.DestinyLive_Integration_Status__c = 'Completed - Success';
            }else if(order.result == 'NA'){
                
                Account Acc = AccMap.get(order.id);
                Acc.DestinyLive_Premium_Membership__c= true;
                Acc.DestinyLive_Integration_Status__c = 'Completed - User Not Found';
            }else if(order.result == 'Failure'){
                Account Acc = AccMap.get(order.id);
                Acc.DestinyLive_Premium_Membership__c= true;
                Acc.DestinyLive_Integration_Status__c = 'Completed - Failure';
           }
            }

            update Accounts;
        }
    }
}

current test 
 
@isTest 
private class Integration_Test{
    static testMethod void IntegrationTest() {
    
  List<Id> AccountIds = new List<Id>();           

  List<Account> AccountList = new List<Account>{};
for(Integer i = 0; i < 200; i++){
        Account Accs = new Account( Name = 'Test' + i, DestinyLive_Premium_Membership_Expiry__c = date.today().adddays(40), DestinyLive_Email_Username__c = 'Success22@knmfld.fdfdf', Receiving_Support__c = true, Support_Expiration__c = date.today().adddays(40), Support_Start__c = date.today().adddays(-40));
        AccountList.add(Accs);
    }
    
   insert AccountList;
    
    
    for ( Account Acc : AccountList) {
    AccountIds.add(Acc.Id);
    }
  
    Test.startTest();
     If(!Test.isRunningTest()){
    Integration.postOrder(AccountIds, True);
    }
    Test.stopTest();


}

}

 
Swayam@SalesforceGuySwayam@SalesforceGuy
Hi

Use HttpCalloutMock for the test and either move the callout (the actual call to the webservice) to afuture method (a method annotated with @future), which will run asynchronously, or, if you are using a Batch (batch processes cannot call futures), make the Batch implement Database.AllowsCallouts.

For the future, since the method will make a callout you have to add the callout=true parameter. Thus the final method will look something like:
 
@future(callout=true)
public static void myFutureMethodThatCallsAWebService(params) {
    ...
}

Please let me know, in case of any doubt.
Hope this helps,

--
Thanks,
Swayam
Developer.mikie.Apex.StudentDeveloper.mikie.Apex.Student
Hey there,

I have the @future(callout=true) in my code. For some reason it is still not passing any line of my code. Would it be possible for you to spply some example code on how I might test this class. It is my first web call class.

Thank you so much for your reply.

Michael