One of the most eagerly awaited Winter ’13 features, at least for developers, has been the ability to test Apex callouts. You can now test HTTP callouts by either
- Creating one or more static resources containing test responses and using the appropriate built-in class — StaticResourceCalloutMock or MultiStaticResourceCalloutMock — to specify the resource(s) to use in testing.
- Implementing one of two new interfaces: HttpCalloutMock, for HTTP (REST) callouts, or WebServiceMock, for Web Service (SOAP) callouts
In this blog entry, I’ll focus on the static resource case. As an example, let’s assume that I’m retrieving JSON Account data from an external service. Here’s a simple callout that retrieves JSON account data, parses it, and returns the resulting list of accounts:
To test this callout, first, I’ll need to create a file, accounts.json, on my local machine containing test data:
Now I go to Setup | Develop | Static Resources, click New Static Resource, enter the name jsonAccounts, and select accounts.json for upload. Notice that Force.com set the MIME type based on the extension of the file I uploaded:
Now to define my test method. I’ll use StaticResourceCalloutMock to provide my Account test data when the getAccounts method executes its callout. First, I need to create an instance of StaticResourceCalloutMock and set the static resource, status code and content type header:
Now I use Test.setMock to tell the Apex runtime I want to use this instance:
Then I can test getAccounts:
And verify I received the expected data:
So, putting it all together into a test method in a test class:
In more elaborate scenarios, I might execute several callouts in a single method. For example, let’s assume I have created a file of JSON-formatted Contact data and uploaded it as the static resource jsonContacts. The method I want to test will retrieve Account data as before, then retrieve the Contacts, and go on to do some processing of the combined Account and Contact data:
I’ll create an instance of MultiStaticResourceCalloutMock, configuring it to provide the appropriate static resource data depending on the URL in the callout request. Here’s the test method in its entirety:
So, testing callouts with static data is very straightforward, but what about more complex use cases? I’ll cover the HttpCalloutMock and WebServiceMock interfaces next time out and show you how to create dynamic response data with dependencies on query parameters or the request body.