0

I am using if(Test.isRunningTest()) condition to set the response code to 200 for code coverage related to my HTTP callout class, so that the success scenario gets covered. But in the coverage details screen, I can see that this function isn't getting covered at all and I am not sure why.

I am adding my callout class code with the screenshot of the coverage screen below. Can anyone please let me know what am I doing wrong? Thanks in advance.

global class fileUploadCallout {
    @future(callout=true)

    global static void Push_to_OB(String body, String boundary, String apiEndPoint, String sfOrderId)
    {   
        OBIntegrationSF__c ins         = OBIntegrationSF__c.getValues('MainConfig');
        String epURL                   = ins.ApiBaseUrl__c;
        String apiURL                  = ins.ApiKey__c;
        HttpRequest request            = new HttpRequest();
        Http ht_tp                     = new Http();  
        HttpResponse response          = null;
        String strMailText;
        
            
        try {              
            system.debug('file blob request akki '+ body);
            request.setEndpoint(epURL+apiEndPoint);      
            request.setBody(body);
            request.setHeader('Authorization', apiURL);
            request.setHeader('Content-Type', 'application/json');
            request.setMethod('POST');
            request.setTimeout(120000);
            
            System.debug('This is the future request sent akki ' + request);

            response = ht_tp.send(request); 

            System.debug('STATUS:'        + response.getStatus());
            System.debug('STATUS_CODE:'   + response.getStatusCode());
            System.debug('RESPONSE_BODY:' + response.getBody()); 

            // sending mail on success

             if(test.isRunningTest()) {
            //     response = new HttpResponse();
            //     response.setHeader('Content-Type', 'application/json');
            //     response.setBody('{"success":true,"code":200,"message":"SUCCESS","data":"Updated","validationErrors":null}');
                 response.setStatusCode(200);
             }

            if(response.getStatusCode() == 200) {
                strMailText = '';
                strMailText += '<div>Hi, <br/> <br/> The IO file synced successfully from SF to OB for the SF Order ID: </b>' + sfOrderId + '<br/>' +
                                                '<br/> You can check the Order record '+ 
                                                '<a href="'+ URL.getSalesforceBaseUrl().toExternalForm()+'/'+sfOrderId+'">here</a><br/><br/> Thank you';
                strMailText += '</body></html>';

                Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
                message.toAddresses = new String[] { 'avasut@test.com' };
                message.optOutPolicy = 'FILTER';
                message.subject = 'IO File Synced Successfully from SF to OB for Order Number ' + sfOrderId;
                message.setHtmlBody(strMailText);
                Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
                Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
            } else {     
                throw new MyException(response.getBody());
            }
            
            System.debug('success akki ' + response);
            
        } catch(System.Exception e) {   

             //Sending mail on failure

            strMailText = '';
            strMailText += '<div>Hi, <br/> <br/> The Syncing of IO file from SF to OB failed for the SF Order ID: </b>' + sfOrderId + '<br/>' +
                                        'Error was: ' + e.getMessage() +  '<br/> You can check the Order record ' +
                                        '<a href="'+ URL.getSalesforceBaseUrl().toExternalForm()+'/'+sfOrderId+'">here</a><br/><br/> Thank you';
            strMailText += '</body></html>';

            Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            message.toAddresses = new String[] { 'avasut@test.com' };
            message.optOutPolicy = 'FILTER';
            message.subject = 'IO File Syncing from SF to OB failed for Order Number ' + sfOrderId;
            //message.plainTextBody = strMailText;
            message.setHtmlBody(strMailText);
            Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
            Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
            
            System.debug(e.getMessage() + ' ' + e.getCause());
        }
    }
}

Code Coverage Screenshot

enter image description here

0
5

Your code in test execution is failed at line response = ht_tp.send(request);. Because you have try-catch block, which catches exceptions, you were not able to observe this exception during test execution.

You have to use HttpCalloutMock Interface for testing callouts, instead of Test.IsRunningTest()

The example from the documentation:

Callout class:

public class CalloutClass {
    public static HttpResponse getInfoFromExternalService() {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://example.com/example/test');
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        return res;
    }
}

CalloutMock 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://example.com/example/test', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"example":"test"}');
        res.setStatusCode(200);
        return res;
    }
}

Callout test class:

@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. 
        HttpResponse res = CalloutClass.getInfoFromExternalService();
        
        // Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        String actualValue = res.getBody();
        String expectedValue = '{"example":"test"}';
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
    }
}

The key moment here is in callout test class:

Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());

After setting this mock in test, when callout class will get to the point of sending the request HttpResponse res = h.send(req); apex framework sets response to what is returned by callout mock class respond method.

1
  • 1
    Thank you for the response, I'll use the Httpcalloutmock interface instead of the Test.isRunningTest() as you suggested. Sep 2 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.