May 29, 2016

Develop & Test Future methods

Implementing @future methods is a good way to get around DDL operation limits and constraints in Salesforce. Methods can be called asynchronously by adding the annotation @future. Salesforce platform framework handles all the queueing and calling when resources are available. Most of the times the calls are made almost immediately (Safe Harbour) post the current transaction context. However a small challenge arises for writing test classes for such methods. Since the call is by-design asynchronous. A simple work around is to wrap the future method call between Test.startTest() and Test.stopTest() methods. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.

Passing variables to future methods could be a bit complicated if you are used to passing sObjects (or their collections). Since future methods are going to run out of the current context, pass a collection of Ids instead and perform a SOQL to retrieve those objects later. If multiple parameters are required in an object structure, use a serializable object with JSON.
public AddressFuture () 
  List addresses = new List();
  AddressHelper ah1 = new AddressHelper('1 here st', 'San Francisco', 'CA', '94105');
  AddressHelper ah2 = new AddressHelper('2 here st', 'San Francisco', 'CA', '94105');
  AddressHelper ah3 = new AddressHelper('3 here st', 'San Francisco', 'CA', '94105');

  //serialize my objects


static void doFutureCall(List addressesSer) 

  AddressHelper currAddress = null;
  for (String ser : addressesSer)
     currAddress = (AddressHelper) JSON.deserialize(ser, AddressHelper.class);
     System.debug('Deserialized in future:'+currAddress.street);
A recursive problem that can occur with improper usage of future methods (and how to avoid it) is explained below in Jeff Douglas's blog. Check the link Prevent Future Recursion below.

Salesforce Doc 1
Salesforce Doc 2
Prevent Future Recursion
Best Practice 1

 Aniket Vast

Whatsapp Button works on Mobile Device only

Start typing and press Enter to search