I need to do a callout to Google Analytics in Salesforce. Based on the documentation, I can't bulkify the request with the records involved, because I can only have one date range.

Is doing a http request in a for loop problematic? I would do this loop in a batch.

for(Account a : accounts) {
    HttpRequest req = new HttpRequest();
    req.setHeader('Content-Type', 'application/json');
    req.setHeader('Authorization', 'Bearer ' + accessToken);

    HTTPResponse res;
    if(Test.isRunningTest()) {
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGAData());
        res = new Http().send(req);
    } else {
        res = new Http().send(req);

    if(res.getStatusCode() == 200) {
        // parse response
    } else {
        // throw error 

1 Answer 1


There's no problem with this code as written, but I suggest you set the mock in your unit test method, not the class itself. As written, you won't be able to get 100% coverage.

Make sure you save any DML operations until all your calls are done, which you should do anyways, because DML in a loop is a bad idea.

  • How do you set the mock in a unit test when you are making a callout from within a batch? Do you just set the mock before calling the batch?
    – Tyler Zika
    Dec 26, 2017 at 18:52
  • 1
    @TylerZika call Test.setMock after the Test.startTest, then queue your batchable call, then use Test.stopTest to execute the batch.
    – sfdcfox
    Dec 26, 2017 at 18:53
  • What if multiple callouts happen in one batch? I do one callout to get a current access token, and the other to get the desired data. The reason my code is like that is I do make multiple callouts in my batch, and was able to achieve close to 100% code coverage, but I agree it's bad practice to put test code in the actual class.
    – Tyler Zika
    Dec 26, 2017 at 18:55
  • @TylerZika you can use the EchoHttpMock design that I use, as shown in salesforce.stackexchange.com/q/141330/2984
    – sfdcfox
    Dec 26, 2017 at 19:20
  • 1
    @Bahman.A There is a limit of 100 calls per transaction and 120 seconds of total callout time. However, calling in a loop is indeed possible as long as you follow the rules.
    – sfdcfox
    Apr 21, 2020 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.