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. 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@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('https://randomuser.me/api', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());

        // Create a fake response
        HttpResponse res = new HttpResponse();
        //set header and body as required/expected
        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.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
@isTest
public class FetchUserDataTest {

    public static testMethod 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. 
    FetchUserData f=new FetchUserData();
    f.RefreshUserData();  
        
    //Check the values are returened correct by asserting them with the Sample JSON values which we have used in MockHttpResponseGenerator class
    //{"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
    system.assertEquals(f.UserData.results[0].name.title,'miss');
    system.assertEquals(f.UserData.results[0].name.first,'katrin');
    system.assertEquals(f.UserData.results[0].name.last,'bartsch');    
}
}


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

No comments:

Post a Comment

Powered by Blogger.