Integration Consuming Salesforce Data - 3

By in
389
Integration Consuming Salesforce Data - 3

Callout testing has both good news and terrible news. The bad news is that callouts are not supported by Apex test methods, and tests that use callouts fail. The good news is that you can “mock” the callout in Salesforce with the testing runtime. Instead of making a real call to the web service during the test, you can specify the response to return using mock callouts.

By calling the web service during testing, you are simply telling the runtime, “I know what this web service will return, so just return this data.” By using mock callouts in your tests, you can make sure that your code is well-covered and that no lines are omitted because of callouts.

Mock Callout Salesforce
Image Source: Salesforce Developers

Let’s establish a class that contains the testing of GET and POST. Although the requests in these instances are in methods and return values, they are substantially the same as the earlier ones.

 

Mock Callout

@isTest

private class WgCalloutsTest {

@isTest static  void testGetCallout() {

// Create the mock response based on a static resource

StaticResourceCalloutMock mock = new StaticResourceCalloutMock();

mock.setStaticResource(‘GetWgResource’);

mock.setStatusCode(200);

mock.setHeader(‘Content-Type’, ‘application/json;charset=UTF-8’);

// Associate the callout with a mock response

Test.setMock(HttpCalloutMock.class, mock);

// Call method to test

HttpResponse result = Wg    Callouts.makeGetCallout();

// Verify mock response is not null

System.assertNotEquals(null,result, ‘The callout returned a null response.’);

// Verify status code

System.assertEquals(200,result.getStatusCode(), ‘The status code is not 200.’);

// Verify content type

System.assertEquals(‘application/json;charset=UTF-8’,

result.getHeader(‘Content-Type’),

‘The content type value is not expected.’);

// Verify the array contains 3 items

Map<String, Object> results = (Map<String, Object>)

JSON.deserializeUntyped(result.getBody());

List<Object> wgRecords = (List<Object>) results.get(‘wgRecords’);

System.assertEquals(3, wgRecords.size(), ‘The array should only contain 3 items.’);

}

}

 

Conclusion

By mocking the callout, you can use the above generic code to test callouts to the external system from within Salesforce.

 

Additional Resources

Cover Photo by Christin Hume on Unsplash

Leave a reply

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