Use Future Methods from (module - Asynchronous Apex) ------------------------------------------------- SOURCE CODE1: public class AccountProcessor { @future public static void countContacts(List accountIds){ List accounts = [Select Id, Name from Account Where Id IN : accountIds]; List updatedAccounts = new List(); for(Account account : accounts){ account.Number_of_Contacts__c = [Select count() from Contact Where AccountId =: account.Id]; System.debug('No Of Contacts = ' + account.Number_of_Contacts__c); updatedAccounts.add(account); } update updatedAccounts;     } } ------------------------------------------------- Source CODE2: @isTest public class AccountProcessorTest { @isTest public static void testNoOfContacts(){ Account a = new Account(); a.Name = 'Test Account'; Insert a; Contact c = new Contact(); c.FirstName = 'Bob'; c.LastName = 'Willie'; c.AccountId = a.Id; Contact c2 = new Contact(); c2.FirstName = 'Tom'; c2.LastName = 'Cruise'; c2.AccountId = a.Id; List acctIds = new List(); acctIds.add(a.Id); Test.startTest(); AccountProcessor.countContacts(acctIds); Test.stopTest();     } }