Skip to main content

Filter any report by current Logged In User in Salesforce | Salesforce Tutorials | Salesforce Development

Understand Queueable Apex with Example and Test Class | #Salesforce



Queueable Apex is similar to @future methods. It is an asynchronous apex method. It allows you to submit jobs for asynchronous processing with some additional benefits comparing to @future methods.

Benefits : 

  • Queueable apex supports non-primitives like SObject and custom Apex types.
  • We can monitor the status and progress of Queueable method using the returned Id of AsyncApexJob.
  • We can chain one job to another by starting the second job from a running job.
Limitations : 
  • It shares limits of async Apex & Governor Limits.
  • In a single transaction you can add maximum 50 jobs in the queue.
  • While chaining jobs, only one child job can exist for each parent job. 


Below example is taken from the Queueable Apex trailhead, the purpose of this is just to share a example of Queueable Apex with test class.


Requirements
Create an Queueable Apex class that inserts Contacts for Accounts.
Create a Queueable Apex class that inserts the same Contact for each Account for a specific state. Write unit tests that achieve 100% code coverage for the class.
  • Create an Apex class called 'AddPrimaryContact' that implements the Queueable interface.
  • Create a constructor for the class that accepts as its first argument a Contact sObject and a second argument as a string for the State abbreviation.
  • The execute method must query for a maximum of 200 Accounts with the BillingState specified by the State abbreviation passed into the constructor and insert the Contact sObject record associated to each Account. Look at the sObject clone() method.
  • Create an Apex test class called 'AddPrimaryContactTest'.
  • In the test class, insert 50 Account records for BillingState "NY" and 50 Account records for BillingState "CA". Create an instance of the AddPrimaryContact class, enqueue the job and assert that a Contact record was inserted for each of the 50 Accounts with the BillingState of "CA".
  • The unit tests must cover all lines of code included in the AddPrimaryContact class, resulting in 100% code coverage.
  • Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.


Solution

AddPrimaryContact

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class AddPrimaryContact implements Queueable {
    Private Contact c;
    Private String s;
    public AddPrimaryContact(Contact con, String state){
        this.c = con;
        this.s = state;
    }
    public void execute(QueueableContext context) {
        List<Account> accList = [SELECT ID, Name ,(Select id,FirstName,LastName from contacts )
                                 FROM ACCOUNT WHERE BillingState = :s LIMIT 200 ];
        List<Contact> conList=new List<Contact>();
        for(Account a: accList){
            Contact cont = c.clone(false,false,false,false);
            cont.AccountId = a.Id;
            conList.add(cont);
        }
          if(conList.size() >0 )
         {
             insert conList;
         }
    }
}


AddPrimaryContactTest

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@isTest
public class AddPrimaryContactTest 
{
     @isTest static void TestList()
     {
         List<Account> accList = new List <Account>();
         for(Integer i=0;i<50;i++)
         {
             accList.add(new Account(BillingState = 'CA', name = 'Acc'+i));
         }
         for(Integer j=0;j<50;j++)
         {
             accList.add(new Account(BillingState = 'NY', name = 'Acc'+j));
         }
         insert accList;

         Contact con = new Contact();
         con.LastName ='Test';
         insert con;
         String state = 'CA';
      
          AddPrimaryContact apc = new AddPrimaryContact(con, state);
          Test.startTest();
            System.enqueueJob(apc);
          Test.stopTest();
      }
 }



If you have any question please leave a comment below.
If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Keep Coding 

Comments

Popular posts from this blog

How to send WhatsApp from Lightning Component Salesforce ?

Send WhatsApp from Lightning Component SalesforceHi folks, in this article I will explain how you can send WhatsApp from Lightning Component using https://wa.me/
In this example I will create a Quick Action button on Contact which will be connected with my Lightning Component.
Please follow the steps below : 
Step 1 : Create a Lightning Component & Apex as shown below
WhatsApp.cmp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30<aura:componentcontroller="Vlog_whatsappCTRL"implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"access="global"><aura:attributename="recordId"type="String"/><aura:attributename="con"type="Contact"/><aura:attributename="msg"type="String"/><aura:handlername="init"action…

Get Parent Id when overriding standard actions with a Lightning Component in salesforce1 app

How to Get Parent Id when overriding standard actions with a Lightning Component in salesforce1 app ?
In this blog I will explain how you can get Parent Id when overriding standard actions with a lightning component.
For example I have changed my Opportunity New button action with a custom Lightning Component. 
Let's create a new account and from the related tab try creating the new Opportunity. Have you noticed any change in URL ?
Let me share the URL with you :  _________________________________________________________________________ https://kapilbatra1-dev-ed.lightning.force.com/lightning/o/Opportunity/new?recordTypeId=0127F000000htlpQAA&additionalParams=accid%3D0017F00002S6g9H%26&inContextOfRef=1.eyJ0eXBlIjoic3RhbmRhcmRfX3JlY29yZFBhZ2UiLCJhdHRyaWJ1dGVzIjp7Im9iamVjdEFwaU5hbWUiOiJBY2NvdW50IiwicmVjb3JkSWQiOiIwMDE3RjAwMDAyUzZnOUhRQVIiLCJhY3Rpb25OYW1lIjoidmlldyJ9LCJzdGF0ZSI6e319&count=3 _________________________________________________________________________
In above URL you …

Modal Popup in Lightning Component Salesforce

How to display modal popup on button's click in Lightning Component ?  To display modal popup in your component first create a button in your Component which will be used to show & hide modal popup.  
1 2 3 4<lightning:button variant="brand" label="Click to Open" title="Click to Open" onclick="{!c.showModel}"/> After that lets add a boolean type attribute above button tag to storeTrue & False value.1<aura:attribute name="showModal" type="boolean"default="false"/>
Copy and paste below code after button in your component. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35<aura:if isTrue="{!v.showModal}"><section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby=…