Apex Future Class
Global class CountContactsClass {
@future
public static void countContactsMethod(List<Id> acIds){
List<Account> acList = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :acIds];
for(Account ac: acList){
ac.Number_of_Contacts__c = ac.Contacts.size();
}
if(!acList.isEmpty()){
update acList;
}
}
}
Anonymous Window | Apex Code
List<Account> acList =[SELECT Id FROM Account];
List<Id> acIdList = new List<Id>();
for(Account ac : acList){
acIdList.add(ac.Id);
}
CountContactsClass.countContactsMethod(acIdList);
Apex Test Class
@isTest
public class CountContactsTestClass {
@istest
private static void testMethodA(){
Account ac = new Account(Name='Test Account');
insert ac;
List<Id> idList = new List<Id>();
idList.add(ac.id);
List<Contact> conList = new List<Contact>();
for(Integer i=1; i<=10; i++){
conList.add(new Contact(LastName=ac.Name + i, AccountId=ac.id));
}
insert conList;
Test.startTest();
CountContactsClass.countContactsMethod(idList);
Test.stopTest();
Account acTest =[SELECT Id,Number_of_Contacts__c FROM Account WHERE Id=:ac.id ];
System.assertEquals(10, acTest.Number_of_Contacts__c);
}
}
Code Coverage