+ Start a Discussion
Shubham Panda 7Shubham Panda 7 

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.
Amit Chaudhary 8Amit Chaudhary 8
Please check below post for same issue
1) https://developer.salesforce.com/forums/?id=906F0000000DBndIAG
 
public class AddPrimaryContact implements Queueable
{
    private Contact c;
    private String state;
    public  AddPrimaryContact(Contact c, String state)
    {
        this.c = c;
        this.state = state;
    }
    public void execute(QueueableContext context) 
    {
         List<Account> ListAccount = [SELECT ID, Name ,(Select id,FirstName,LastName from contacts ) FROM ACCOUNT WHERE BillingState = :state LIMIT 200];
         List<Contact> lstContact = new List<Contact>();
         for (Account acc:ListAccount)
         {
                 Contact cont = c.clone(false,false,false,false);
                 cont.AccountId =  acc.id;
                 lstContact.add( cont );
         }
         
         if(lstContact.size() >0 )
         {
             insert lstContact;
         }
             
    }

}
Test class like below
@isTest
public class AddPrimaryContactTest 
{
     @isTest static void TestList()
     {
         List<Account> Teste = new List <Account>();
         for(Integer i=0;i<50;i++)
         {
             Teste.add(new Account(BillingState = 'CA', name = 'Test'+i));
         }
         for(Integer j=0;j<50;j++)
         {
             Teste.add(new Account(BillingState = 'NY', name = 'Test'+j));
         }
         insert Teste;

         Contact co = new Contact();
         co.FirstName='demo';
         co.LastName ='demo';
         insert co;
         String state = 'CA';
      
          AddPrimaryContact apc = new AddPrimaryContact(co, state);
          Test.startTest();
            System.enqueueJob(apc);
          Test.stopTest();
      }
 }
Sample test class with Assert as well
 
@isTest
public class AddPrimaryContactTest {

    @isTest static void testQueueable(){
        //<-----@testSetup
        List<Account> accounts = new List<Account>();
        for (Integer i = 0; i < 50; i++){accounts.add(new Account(name = 'acc' + i, BillingState = 'NY')); }
        for (Integer i = 50; i < 100; i++){accounts.add(new Account(name = 'acc' + i, BillingState = 'CA')); }
        insert accounts;
        
      	String strState = 'CA';
        Contact cont = new Contact(LastName = 'TstsName');
        AddPrimaryContact updater = new AddPrimaryContact(cont, strState);
        //<-----@testSetup

        //<-----@testExecution
        Test.startTest();
        	System.enqueueJob(updater);
        Test.stopTest();
        //<-----@testExecution
        
        //<-----@testResult
        System.assertEquals(50, [select count() from Contact where accountID IN (SELECT id FROM Account WHERE BillingState = :strState)]);   
        //<-----@testResult
    }
}

Let us know if this will help you

 
Chetan KapaniaChetan Kapania
Hi Amit,

I tried the code mentioned above and Apex class works as expected, but while writing test class with Assert I am getting an error message:
System.AssertException: Assertion Failed: Expected: 50, Actual: 0

Any idea what could be the reason behind it. 

Regards
Chetan
 
andreCandyGodandreCandyGod
Very late response but if anyone else is having that issue I'm guessing you didn't insert the accounts or I would double check the assert SOQL since it might not be functioning as intended. Let me know if that helps.
 
Robin Bansal 35Robin Bansal 35
public class AddPrimaryContact implements Queueable{
    private Contact c;
    private String state;
    public AddPrimaryContact(Contact contact, String state){
        this.c = contact;
        this.state = state;
    }
    
    public void execute(QueueableContext context){
        List<Account> accounts = [Select ID, Name From Account WHERE BillingState =:state LIMIT 200];
        List<Contact> contacts = new List<Contact>();
        for(Account account: accounts){
            Contact con = c.clone(false, false,false, false);
            con.AccountId = account.Id;
            contacts.add(con);
            
        }
        if(contacts.size()>0){
            insert contacts;
        }
    }

}
------------------------------------------------
@isTest
public class AddPrimaryContactTest {
    @testSetup
    static void setup(){
        List<Account> testAccounts = new List<Account>();
        for(Integer i=0; i<50; i++){
            testAccounts.add(new Account(BillingState = 'NY', name = 'QueueTest ' + i));
        }
        for(Integer j=0; j<50; j++){
            testAccounts.add(new Account(BillingState = 'CA', name = 'QueueTest ' + j));
        }
        insert testAccounts;
        
    }
    
    static testMethod void test(){
        Contact con = new Contact(FirstName = 'Queueable', LastName = 'Apex');
        insert con;
        String state = 'CA';
        Test.startTest();
        AddPrimaryContact primContact = new AddPrimaryContact(con, state);
        System.enqueueJob(primContact);
        Test.stopTest();
        
        System.assertEquals(50, [SELECT count() FROM Contact WHERE accountId IN (Select id from Account WHERE BillingState =:state)]);
    } 

}
DAN LI 10DAN LI 10
Hi Guys,
I will share my code below, it works. Hople it's helpful to someone .

1 ,Create an Apex class called 'AddPrimaryContact' :

public class AddPrimaryContact implements Queueable {
    
    private String st;
    private Contact primecontact;
    
    public AddPrimaryContact(Contact aContact, String aState) {
        this.st=aState;
        this.primecontact = aContact;
    }
    public void execute(QueueableContext context) {
        List<Account> accounts = [select name from account where billingstate=:st LIMIT 200];
        List<Contact> contacts = new List<Contact>();
        for (Account acc : accounts) {
           contact con=primecontact.clone(false,false,false,false);
           contacts.add(con);
        }
        insert contacts;
}
}

2 ,Create an Apex test class called 'AddPrimaryContactTest':

@isTest
public class AddPrimaryContactTest {
@testSetup 
    static void setup() {
        List<Account> accounts = new List<Account>();
        // add 50 NY account
        for (Integer i = 0; i < 50; i++) {
        accounts.add(new Account(Name='NY'+i, billingstate='NY'));
        }
         // add 50 CA account
        for (Integer j = 0; j < 50; j++) {
        accounts.add(new Account(Name='CA'+j, billingstate='CA'));
           }
        insert accounts;
      }
       static testmethod void testQueueable(){
        contact a=new contact(Lastname='mary', Firstname='rose'); 
        Test.startTest();        
        AddPrimaryContact updater=new AddPrimaryContact(a, 'CA');
        System.enqueueJob(updater);
        Test.stopTest(); 
      
        System.assertEquals(50, [SELECT count() FROM Contact WHERE Lastname='mary' AND Firstname='rose']) ;                      
    }   
}
 
Santosh-GaddamSantosh-Gaddam
Thanks Dan! it worked for me.
Chetan KapaniaChetan Kapania
Thanks Dan! it worked for me.
Mayur Maheta 14Mayur Maheta 14

Hi Guys,
I share my code, it's working fine. I hope it's helpful to someone.

1) Create an Apex class called AddPrimaryContact :

public class AddPrimaryContact implements Queueable {
    private Contact c;
    private String state;
    public AddPrimaryContact(Contact c, String state){
        this.c = c;
        this.state = state;
    }
    public void execute(QueueableContext context){
        List<Account> ListAccount = [SELECT ID, Name ,(Select id,FirstName,LastName from contacts ) FROM ACCOUNT WHERE BillingState = :state LIMIT 200];
        List<Contact> lstContact = new List<Contact>();
        for(Account acc : ListAccount){
            Contact cont = c.clone(false,false,false,false);
            cont.AccountId = acc.id;
            lstContact.add(cont);
        }
        if(lstContact.size() > 0){
            insert lstContact;
        }
        
    }
}

2 ) Create an Apex test class called AddPrimaryContactTest:

  • Note: Add state in State and Country/Territory Picklists, and pass with the country code.

@isTest
public class AddPrimaryContactTest {
    static testmethod void TestList(){
        List<Account> Teste = new List<Account>();
        for(Integer i=0;i<50;i++){
            Teste.add(new Account(BillingCountryCode = 'AD', BillingState='CA',Name='Test'+i));
        }
        for(Integer j=0;j<50;j++){
            Teste.add(new Account(BillingCountryCode = 'AD',BillingState='NY',Name='Test'+j));
        }
        insert Teste;
        Contact co = new Contact();
        co.FirstName = 'demo';
        co.LastName = 'demo';
        insert co;
        String state = 'CA';
        
        AddPrimaryContact apc = new AddPrimaryContact(co,state);
        Test.startTest();
        System.enqueueJob(apc);
        Test.stopTest();
    } 
}

Mohamed Mrabet 7Mohamed Mrabet 7
Hello guys,
The sObject clone() method four arguments are set by default to 'false'. Therefore, there is no need to explicitly specify that when you call that method.
Also, there is no need for having an inner query to get the Contacts for each Account.
Hope this helps!
- M.
Amit Jha 20Amit Jha 20

Please understand use of this before using it. we do not need this here.

public class AddPrimaryContact implements Queueable {
    private Contact contacts;
    private String state;
        
    public AddPrimaryContact(Contact newContact, String st) {
        contacts = newContact;
        state = st;
        
    }
        public void execute(QueueableContext qc) {
            List<Account> ls = [select id,name,BillingState from Account where BillingState =:state limit 200];
            List<Contact> listOfContacts = new List<Contact>();
            for(Account acc: ls) {
                Contact cont = contacts.clone(false,false,false,false);
                cont.accountId = acc.Id;
                cont.MailingState= acc.BillingState;
                listOfContacts.add(cont);
            }
            
            insert listOfContacts;
            
        }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@isTest
public class AddPrimaryContactTest {

    @testSetup
    static void setup() {
        List<Account> accList = new List<Account>();
        
        for(Integer i=0;i<50;i++) {
            accList.add(new Account(Name='Test Acc'+i,BillingState='NY'));
        }
        
        for(Integer j=0;j<50;j++) {
            accList.add(new Account(Name='Test2 Acc2'+j,BillingState='CA'));
        }
        insert accList;
        
        Contact con = new Contact(lastName = 'Test Contact');
        insert con;
    }
    
    static testMethod void test() {
        Test.startTest();
            Contact con =[SELECT id,name,lastName from Contact where lastName Like '%Test%' limit 1];
            String state = 'CA';
        
            AddPrimaryContact apc = new AddPrimaryContact(con,state);
            System.enqueueJob(apc);
        
            System.assertEquals(50, [Select count() from Contact where accountid in :[SELECT id from Account where name like '%Test2%']]);
        Test.stopTest();
        
    }
}

Hope this helps :) .....happy coding

 

vanamamuralivanamamurali
I tried all above code but it is not working for me .. I'm getting below error while running test cases.
System.LimitException: Too many SOQL queries: 101

please suggest me testclass.

Thanks in advance.