Skip to Content

Demystifying Salesforce REST API Part 3: Unit Testing in Apex

In the previous post Salesforce Rest API Integration Part 2: Parsing JSON In Salesforce we have successfully completed our development to fetch user info from Random user and displaying the same in Visual force page.

In this post we will be carrying out the Apex test class development for the same.

STEP 1: Create Mock Response

For Testing Rest Services we have to first setup Mock Responses class which will give us sample responses as expected by the main class. For this we will implement the standard HttpCalloutMock interface as below. 

@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {

    // Implement the interface method to mock the HTTP response
    global HTTPResponse respond(HTTPRequest req) {
       
        // Check the request endpoint and method (just being extra safe)
        System.assertEquals('https://randomuser.me/api', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());

        // Create and configure the fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody(
            '{"results":[{' +
                '"gender":"female",' +
                '"name":{"title":"miss","first":"katrin","last":"bartsch"},' +
                '"location":{"street":"4334 waldweg","city":"mannheim","state":"mecklenburg-vorpommern","postcode":20130},' +
                '"email":"katrin.bartsch@example.com",' +
                '"login":{' +
                    '"username":"organicpeacock621",' +
                    '"password":"red123",' +
                    '"salt":"OhICfV2g",' +
                    '"md5":"0ceb0373cfd571a3e6c5fcacd99809dd",' +
                    '"sha1":"b28b5c5cef0373df8dc5a6512d872a754d4fee6f",' +
                    '"sha256":"6f1ea35b53687719a53fe06fce777e19cd1c834835d23af7939abd97dbf6bfd5"' +
                '},' +
                '"registered":1355929404,' +
                '"dob":1090756780,' +
                '"phone":"0236-5399055",' +
                '"cell":"0174-2134916",' +
                '"id":{"name":"","value":null},' +
                '"picture":{' +
                    '"large":"https://randomuser.me/api/portraits/women/7.jpg",' +
                    '"medium":"https://randomuser.me/api/portraits/med/women/7.jpg",' +             '"thumbnail":"https://randomuser.me/api/portraits/thumb/women/7.jpg"' +
                '},' +
                '"nat":"DE"' +
            '}],' +
            '"info":{"seed":"496aac1fa1fe668b","results":1,"page":1,"version":"1.0"}}'
        );
        res.setStatusCode(200);

        return res;
    }
}

STEP 2: Create Test Class 

Create a test class by using Test.setmock to redirect all the requests from here to the mock response generator class we have created above.

@isTest
public class FetchUserDataTest {

    public static testMethod void testCallout() {
        // Set the mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());

        // Instantiate and invoke the method to test
        FetchUserData f = new FetchUserData();
        f.RefreshUserData(); 

        /*
         * Assert returned values based on the mock JSON in MockHttpResponseGenerator:
         * {
         *   "results": [
         *     {
         *       "name": {
         *         "title": "miss",
         *         "first": "katrin",
         *         "last": "bartsch"
         *       }
         *     }
         *   ]
         * }
         */

        System.assertEquals('miss', f.UserData.results[0].name.title, 'Mismatch in title');
        System.assertEquals('katrin', f.UserData.results[0].name.first, 'Mismatch in first name');
        System.assertEquals('bartsch', f.UserData.results[0].name.last, 'Mismatch in last name');   
    }
}

As noted in the previous post JSON2Apex is an amazing tool which generates both Apex class and test class. Have a look at the same. 

 This brings out the end of how to consume rest API services in Apex, what we will see next is how to expose Rest Services in Apex

Demystifying Salesforce REST API Part 2: Parsing JSON in Salesforce