Site icon WedgeCommerce

Bypassing web callouts in test classes

Test classes are an essential part of any application that we download from or upload to salesforce. They don’t just cover code, but also show that the code is working fine and no issue was encountered. For any package to be uploaded it is necessary that at least 75% of the code coverage must be reached. The problem arises, when the test class encounters a web service callout and it halts execution while throwing an error. Lets see how can we update controller class for bypassing web callouts in test classes.

APEX and VF Code

public class wc_class {
    public string endpoint;
    public string total { get; set;}
    
    public wc_class(){
        endpoint = 'https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v39.0/query/?q=SELECT+Id,Name+from+Account';
        doCallout();
    }
    
    public void doCallout(){
        HttpRequest req = new HttpRequest();
        req.setEndPoint(endpoint);
        req.setMethod('GET');
        string autho = 'Bearer '+ userInfo.getsessionId();
        req.setHeader('Authorization', autho);

        //To be replaced
        HTTP method = new HTTP();
        HttpResponse res = method.send(req);
        //Till here
        string responseBody = res.getBody();
        total = responseBody.substring(responseBody.indexOf('totalSize":') + 11, responseBody.indexOf(','));
    }
}

I have written an APEX class for this example. This class simply makes a callout to the salesforce rest api and fetches the total count of accounts. Now when we will run this class after attaching it with a vf page it will make the callout, like I have already done it in the following example.

<apex:page controller="wc_class">
<apex:outputText value="{!total}"/>
</apex:page>

Now that our page is complete we can run it and test its functioning. However the main part is still remaining, which is a test class for our controller.

*Important*: You might encounter an error about unauthorised endpoint when you preview this page. To resolve that issue add the page’s host name to the remote site settings. For that purpose you can refer the following blog’s Prerequisites: https://wedgecommerce.com/fetch-records-rest-api-apex-class-salesforce/

Test Class

@isTest
public class wc_classTest {
	static testMethod void Testwc(){
        wc_class wcc = new wc_class();
        system.assertEquals(wcc.total, '0');
    }
}

With this done we can run the test in order to check code coverage. However, this test class is bound to fail because we have directly used a callout and when the test class will reach that point it will throw an exception. This is the main part of the blog, how to handle this scenario. Well the answer is simple, we will put up a condition in our controller to control the path of execution for test class and normal pages.

In the code of controller replace the two lines we have marked in comments, with following code:

string responseBody;
        if(Test.isRunningTest()){
            responseBody = 'totalSize":0,';
        }else{
            HttpResponse res = method.send(req);
            responseBody = res.getBody();
        }

Here we are using the standard test class method isRunnignTest() which tells the controller if a test is running or not. For test condition we use different code, and the actual code stays in the else part of the condition. Try running the test once more and see the difference in results. The updated result will give a fully executed code of the class with just skipping the callout part.

Support

That’s all about bypassing callouts in test classes, for any further queries feel free to contact us at:

https://wedgecommerce.com/contact-us/

Or let us know your views on how to make this code better, in comments section below.

Exit mobile version