Salesforce Apex

Requirement: Create Fake Response For Apex Test Class

If you did some http callout in your apex class . you need to cover it from your test class sometimes we get stuck while we are covering http request callout in test class.

to cover callout in test class you need to generate fake resonse ,

here is the code to generate  fake response  after generating fake response you need to call fake response method in your test class

Fake response generator class

global class MockHttpResponseGenerator implements HttpCalloutMock 
{
    global HTTPResponse respond(HTTPRequest req) 
    {
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"foo":"bar"}');
        res.setStatusCode(200);
        return res;
    }
}

Now in your test class you can call your mockclass like

 

@isTest
public class Yourtestclassname
{
    public static testMethod void TestMethod()
    {
       
        // this is used for test http response we need to generate  a fake response from another class

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

 

NOTE :  To mock a callout if the code that performs the callout is in a managed package,           call Test.setMock from a test method in the same package with the same namespace.

Example :

Fake response generator class (IF COde is in managed package)

@istest
global class MockHttpResponseGenerator implements HttpCalloutMock 
{
    global HTTPResponse respond(HTTPRequest req) 
    {
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"foo":"bar"}');
        res.setStatusCode(200);
        return res;
    }
}

 

Hits: 3554

Share Post

By Himanshu Rana

My Name is Himanshu Rana, 23 Years young, born and grow up in Ghaziabad, India. A High Spirited Salesforce Admin, Developer and a Blogger. I currently work at Wakencode Technologies,

Leave a Reply

Your email address will not be published. Required fields are marked *