Everytime I solve a problem, another appears. More than a problem, I would say a SalesForce restrictions.

So, I want to test some code (which makes a web service call in order to display some data) with different user profiles. In order to accomplish that, I'm using the System.runAs(User) method.

First problem was that it's mandatory to use this method within a test method.

Solved that, easy. I've included the code in a TestMethod.

Now the second problem is, within a TestMethod is not possible to make a web service callout.

¿Which are my options here??!!


2 Answers 2


Here is part of a test that makes use of a class that implements HttpCalloutMock to return responses that cause various parts of controller logic (where the controller includes a callout) to execute. The mock can also assert that it was passed the correct data in the request.

private class FacebookCallbackControllerTest {
    private static final String IDENTITY = '[email protected]';
    private class FacebookMock implements HttpCalloutMock {
        public HTTPResponse respond(HTTPRequest req) {
            if (req.getMethod() == 'POST') {
                // Assume call is to get access token
                HttpResponse res = new HttpResponse();
                res.setHeader('Content-Type', 'application/x-www-form-urlencoded');
                return res;
            } else if (req.getEndpoint().contains('access_token')) {
                // Assume call is to get email
                HttpResponse res = new HttpResponse();
                res.setHeader('Content-Type', 'application/json');
                res.setBody('{"email":"' + IDENTITY + '"}');
                return res;
            } else {
                System.assert(false, 'unexpected endpoint=' + req.getEndpoint());
                return null;
    static void testEmail() {
        Test.setMock(HttpCalloutMock.class, new FacebookMock());
        FacebookCallbackController controller = new FacebookCallbackController();
        PageReference nextPr = controller.init();
        System.assertEquals(IDENTITY, nextPr.getParameters().get('email'));

As commented earlier, some documentation links on mocks are:


I don't think you can test the actual web service from your apex test class. But you can test the apex around the callout by wrapping the callout:

if (!Test.isRunningTest()) {
  • 2
    Better to use mocking - see the links in the comment on the question.
    – Keith C
    Commented May 15, 2015 at 12:18
  • Agreed. Mocking is the ideal solution.
    – James
    Commented May 15, 2015 at 14:06
  • This should be done only when there is very complex response and it is not possible to create a mock for that. For simple web services, we should use HttpCalloutMock only.
    – ajinkyah
    Commented May 15, 2015 at 16:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .