Concepts or coding lessons of Salesforce that you can implement easily

How to write Test class for HTTPCallouts in Salesforce?

To deploy or package Apex, 75% of your code must have test coverage. By default, test methods don’t support HTTP callouts, so tests that perform callouts fail. Enable HTTP callout testing by instructing Apex to generate mock responses in tests, using Test.setMock.

This is a full example that shows how to test an HTTP callout.

Sample HTTPCallout Class:


public class AnimalLocator {
    public static String getAnimalNameById(Integer id) {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('http://example.com/example/test/animals/'+id);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        String strResp = '';
        if (response.getStatusCode() == 200) {
           Map < String, Object > results = (Map < String, Object >) JSON.deserializeUntyped(response.getBody());
           Map < String, Object > animals = (Map < String, Object >) results.get('animal');
           strResp = string.valueof(animals.get('name'));
        }
        return strResp ;
    } 
}

Sample HTTP Mock Callout Class: 


@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest request) {
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animal": {"id":1, "name":"Tiger"}}');
        response.setStatusCode(200);
        return response;
    }
}

Test Class for HTTPCallouts: 


@isTest
private class AnimalLocatorTest {
    static testMethod void testPostCallout() {
        Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock()); 
        String strResp = AnimalLocator.getAnimalNameById(1);
    }
}

Done thats it 👍!!!!


Latest Salesforce Interview Questions and Answers:

Salesforce Interview Questions - Part 1

Salesforce Interview Questions - Part 2

Salesforce Interview Questions - Part 3

Salesforce Interview Questions - Part 4

Salesforce Interview Questions - Part 5

Salesforce Interview Questions - Part 6

Salesforce Interview Questions - Part 7

Salesforce Interview Questions - Part 8

More Salesforce Blogs:

Check out Salesforce Daily Limit Only in 5 Simplest Steps
Learning Pagination In Salesforce Is Not Difficult At All ! You Just Need 3 Easy Steps
How To Learn Get Field Values From Visualforce Page To Apex Class Controller Without Losing Your Mind
Main Difference Between ISBLANK And ISNULL in Salesforce
How To Get Total Amount Of Records Processed In Batch Job In 10 Minutes And Still Look Your Best 
Export VisualForce Data into Excel Sheet in 3 Easiest Steps
7 Easy Steps to Generate Apex Class From WSDL In Salesforce
Simplest Way To Find Number of Days Between Two Dates in Salesforce
3 Easy Steps To Send Emails With Attachment From Your Apex Class In Salesforce
How Insert Comma In Formula Fields Can Help You Improve Your Productivity
Simple Guidance For You In Access Of Subquery Field Value Using Apex - Upwards Traversal.
Access Subquery Field Value Using Apex in 2 Easy Steps- Downwards Traversal

How Learning Enable Inline Editing In Visual Force Pages Could Save Your Money And Time

Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.