function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kumar 197kumar 197 

Test Class For Number of Contacts on Account???

trigger ContactCount on Contact (after insert, after update, after delete, after undelete) {
    
    if(Trigger.isinsert || Trigger.isupdate || trigger.isdelete || Trigger.isundelete){
       
        ContactCount.countcontacts(trigger.new,trigger.old);
        
    }
}

-----------
public class ContactCount {
    public static void countcontacts(List<contact> newcontact,List<contact> oldcontact){
     
        set<id> accids= new set<id>();
                try{
        if(newcontact !=null){
            for(Contact c:newcontact){
                if(c.AccountId!=null){
                accids.add(c.accountid);
                }
            }      
       }if(oldcontact!=null){
            for(Contact c:oldcontact){
                accids.add(c.accountid);
            }
       }
     List<Account> acc = [Select id, Number_of_Contacts__c,(Select id from Contacts) from Account where id IN: accids];
        if(acc!=null){
        for(Account accValue:acc){
            accValue.Number_of_Contacts__c = accValue.Contacts.size();
        } 
        }
        if(!acc.isempty()){
        update acc;
        }
        }
        catch(exception e){
            System.debug('Get Message'+e.getMessage());
        }
    } 
}
Best Answer chosen by kumar 197
CharuDuttCharuDutt
Hii Kumar
Try Below Test Class 100% Coverage!
@isTest
public class ContactCount Test {
@isTest
    public Static Void UnitTest(){
        list<Contact>lstCon = new list<Contact>();
        Account Acc = new account();
        Acc.name ='test';
        insert Acc;
        
        Account Acc2 = new account();
        Acc2.name ='test2';
        insert Acc2;
        
        for(Integer i=0;i<5;i++){
        Contact Con = new Contact();
        Con.LastName = 'TestCon'+i;
        Con.AccountId = Acc.Id;
            lstCon.add(Con);
        }
        Contact Con = new Contact();
        Con.LastName = 'TestCon';
        Con.AccountId = Acc.Id;
        Insert Con;
        insert lstCon;
      
        list<account> sacc  = [select id,Number_of_Contacts__cfrom Account where id = :Acc.Id];
         system.debug(sacc);
        Con.AccountId = Acc2.Id;
       
       
      	Update Con;
        
        list<account> sacc2  = [select id,Number_of_Contacts__cfrom Account where id = :Acc2.Id];
         system.debug(sacc2);
        list<account> sacc4  = [select id,Number_of_Contacts__cfrom Account where id = :Acc.Id];
         system.debug(sacc4);
Delete Con;
         list<account> sacc3 = [select id,Number_of_Contacts__cfrom Account where id = :Acc2.Id];
        system.debug(sacc3);
       
        
    }
}
Please Mark It As Best Answer If It Helps
Thank You!