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

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:

public class CalloutAccounts {
    public static List<Account> getAccounts() {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://api.example.com/accounts');
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        String jsonData = res.getBody();
        List<Account> accounts = 
            (List<Account>)JSON.deserialize(jsonData, List<Account>.class);
        return accounts;
    }
}

To test this callout, first, I’ll need to create a file, accounts.json, on my local machine containing test data:

[
  {
    "Name": "sForceTest1",
    "Website": "http://www.sforcetest1.com"
  },
  {
    "Name": "sForceTest2",
    "Website": "http://www.sforcetest2.com"
  },
  {
    "Name": "sForceTest3",
    "Website": "http://www.sforcetest3.com"
  }
]

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:

StaticResourceCalloutMock mock = new StaticResourceCalloutMock(); 
mock.setStaticResource('jsonAccounts');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');

Now I use Test.setMock to tell the Apex runtime I want to use this instance:

Test.setMock(HttpCalloutMock.class, mock);

Then I can test getAccounts:

Test.startTest();
List<Account> accounts = CalloutAccounts.getAccounts();
Test.stopTest();

And verify I received the expected data:

System.assertEquals(3, accounts.size()); 
System.assertEquals('sForceTest1', accounts[0].Name);
System.assertEquals('sForceTest2', accounts[1].Name);
System.assertEquals('sForceTest3', accounts[2].Name);

So, putting it all together into a test method in a test class:

@isTest
private class CalloutAccountsTest {
    @isTest static void testCallout() {
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('jsonAccounts');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json');

        // Set the mock callout mode
        Test.setMock(HttpCalloutMock.class, mock);

        // Call the method that performs the callout
        Test.startTest();
        List accounts = CalloutAccounts.getAccounts();
        Test.stopTest();

        // Verify response received contains values returned by
        // the mock response.
        System.assertEquals(3, accounts.size());
        System.assertEquals('sForceTest1', accounts[0].Name);
        System.assertEquals('sForceTest2', accounts[1].Name);
        System.assertEquals('sForceTest3', accounts[2].Name);
    }
}

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:

public class ProcessAccountsContacts {
    public static String getJSON(String url) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        return res.getBody();
    }

    public static Integer processAccountsContacts() {
        String jsonData = getJSON('http://api.example.com/accounts');
        List<Account> accounts = 
            (List<Account>)JSON.deserialize(jsonData, List<Account>.class);

        jsonData = getJSON('http://api.example.com/contacts');
        List<Contact> contacts = 
            (List<Contact>)JSON.deserialize(jsonData, List<Contact>.class);

        // 'Processing'
        Integer result = accounts.size() + contacts.size();
        return result;
    }
}

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:

@isTest
private class ProcessAccountsContactsTest {
    @isTest static void testCallout() {
        MultiStaticResourceCalloutMock multimock = 
            new MultiStaticResourceCalloutMock();
        // 3 test accounts
        multimock.setStaticResource('http://api.example.com/accounts', 
            'jsonAccounts');
        // 3 test contacts
        multimock.setStaticResource('http://api.example.com/contacts', 
            'jsonContacts');
        multimock.setStatusCode(200);
        multimock.setHeader('Content-Type', 'application/json');

        // Set the mock callout mode
        Test.setMock(HttpCalloutMock.class, multimock);

        // Call the method that performs the callouts
        Test.startTest();
        Integer result = ProcessAccountsContacts.processAccountsContacts();
        Test.stopTest();

        // Verify response is as expected, given the test data
        System.assertEquals(6, result);
    }
}

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.

tagged , , , , Bookmark the permalink. Trackbacks are closed, but you can post a comment.
  • Jason

    I was pretty pumped about this feature, but when going to use it I ran into some serious limitations. I can’t create any test data in my test before executing my mock callout without getting a callout exception about pending transactions. Is there any way to get around this?

    • http://blog.superpat.com/ Pat Patterson

      That’s a good question – investigating.

    • Anshul Verma

      Faced similar situation. We did something like this, which worked for us.

      // create test data

      System.Runas( [select id from User where id = :UserInfo.getUserId()] )
      {
      // test initiation and assertions
      }

      • Jason

        I tried creating my data in a runAs block as well as running the test in a runAs block thinking it would be like getting around modifying a setup object in a test, but I’m still getting the error.

        • http://blog.superpat.com/ Pat Patterson

          I’ve confirmed that you cannot use mock callouts with pending DML. The problem is that we would want to catch the erroneous case where non-test code was doing DML before a callout. Filing a bug to see if we can maybe allow DML and callouts where there is a Test.startTest() between them.

  • Daniel Hoechst

    Is there a way to access zipped static resources in a StaticResourceCalloutMock? I have a lot of test cases and would like my mocks to all be in one zip file for ease of management.