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
p sonwanep sonwane 

count number of contact from account . below is working code can anyone tell test class for this

Apex code
public class CountContactHandler {
    public static void CountContactHelper(List<contact> newcontact, List<contact> oldcontact){
        set<id> accIds= new set<id>();
        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> accList = [Select Id, NoofContacts__c, (Select id from Contacts) from Account where Id IN :accIds];
         
        if(accList!=null){
            for(Account acc : accList){
                acc.NoofContacts__c = acc.Contacts.size();
            } 
        }
         
        if(!accList.isEmpty()){
            update accList;
        }
    } 
}




Test class : 

@isTest
public class CountContactHandlerTest {
    @isTest
    public static void CountContactHelpertest(){ 
        //Create sample data 
        List<Account> accList = new List<Account>();
        
        for(Integer i=1;i<=5;i++){
            Account acc = new Account();
            acc.Name='Test'+i;
            acc.Industry='Energy';
            accList.add(acc);
        } 
        
        // insert data
        Test.startTest();
        insert accList;
        Test.stopTest();
        List<Contact> conList = [Select Id from Contact where AccountId =:accList[0].Id];
        System.assert(conList!=null, 'Contact is not created');
        
    }
}
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

Can you confirm what excatly issue with your test class? Is it not covering the code or is it failing.

Thanks,
 
Dosbol TDosbol T
Hi there, I have changed a bit your code, The null check for accList was removed, since accList is guaranteed to be a list, and List objects can never be null.
 
public class CountContactHandler {
    public static void CountContactHelper(List<Contact> newContacts, List<Contact> oldContacts){
        Set<Id> accIds = new Set<Id>();

        if(newContacts != null){
            for(Contact c : newContacts){
                if(c.AccountId != null){
                    accIds.add(c.AccountId);
                }
            }      
        }
         
        if(oldContacts != null){
            for(Contact c : oldContacts){
                accIds.add(c.AccountId);
            }
        }
         
        List<Account> accList = [SELECT Id, NoofContacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :accIds];
         
        if(accList != null){
            for(Account acc : accList){
                acc.NoofContacts__c = acc.Contacts.size();
            } 
        }
         
        if(!accList.isEmpty()){
            update accList;
        }
    } 
}

and test class:
 
@isTest
private class CountContactHandlerTest {
    private static testMethod void testCountContactHelper() {
        // Create test data
        Account testAccount = new Account(Name='Test Account');
        insert testAccount;

        Contact testContact1 = new Contact(LastName='Test Contact 1', AccountId=testAccount.Id);
        Contact testContact2 = new Contact(LastName='Test Contact 2', AccountId=testAccount.Id);
        Contact testContact3 = new Contact(LastName='Test Contact 3', AccountId=testAccount.Id);
        insert new List<Contact>{testContact1, testContact2, testContact3};

        // Call the method to be tested
        CountContactHandler.CountContactHelper(new List<Contact>{testContact1, testContact2}, new List<Contact>{testContact3});

        // Query the updated accounts
        List<Account> updatedAccounts = [SELECT Id, NoofContacts__c FROM Account WHERE Id = :testAccount.Id];

        // Verify the results
        System.assertEquals(1, updatedAccounts.size(), 'There should be 1 updated account');
        System.assertEquals(3, updatedAccounts[0].NoofContacts__c, 'The updated account should have 3 contacts');
    }
}

Hope it helps you.
​​​​​​​​​​​​​​
p sonwanep sonwane
Hi sai praveen test is shwoing success but coverage is 44 %
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

Is this called in after trigger context. Can you share the trigger as well for the same.

Thanks,
 
p sonwanep sonwane
Hi Sai ,
below is the trigger code 

trigger CountContactsOnAccount on Contact (after insert, after update, after delete, after undelete) {
    //call handler for best practice
    if(Trigger.isinsert || Trigger.isupdate || trigger.isdelete || Trigger.isundelete){
        CountContactHandler.CountContactHelper(trigger.new, trigger.old);
    }
}
Sai PraveenSai Praveen (Salesforce Developers) 
Hi ,

Can you try the below test class. It gave me 100% Coverage
 
@istest
public class CountContactHandlerTest {
@isTest static void testUpsertCase() {
    
    Account acc= new Account();
    acc.name= 'sample account';
    insert acc;
    Account acc2= new Account();
    acc2.name= 'sample account2';
    insert acc2;
    Contact con= new Contact();
    con.lastname='sample cpontact';
    con.AccountId=acc.id;
    insert con;
    con.accountid=acc2.id;
    update con;
List<Account> accList = [Select Id, NoofContacts__c, (Select id from Contacts) from Account where Id = :acc2.id];
            System.assertEquals(1,accList[0].Contacts.size());

}
}


Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,