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
ARUL BERNARD I 6ARUL BERNARD I 6 

How write test class for Aggregate result

Hi,
    I have a rating field in contact and overall rating filed in the account. If I added a new account or update the rating field it should sum and update in overall rating this my scenario.How to write a test class for this code.
Apex code:
trigger Overallrating on Contact (after insert,after update,after delete,after undelete){
    
    Set<Id> accIdset = new Set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.isundelete){
        for(contact con : trigger.new)
        {
            if(con.AccountId != null)
            {
                accIdset.add(con.AccountId); 
            }
        }
    }
    
    else if(trigger.isdelete)
    {  
        for(contact con : trigger.old)
        {
            if(con.AccountId != null)
            {
              accIdset.add(con.AccountId);
            }
        }
    
    }  
    
    
    account acc=new account();
        
      List<AggregateResult>  lstAggregation = new list<AggregateResult>();
      List<Account> overallrating = new List<Account>();
      
      
      for(AggregateResult ar: [select sum(Rating__c) ratid,count(id) countid,AccountId accId from contact where accountid = :accIdset group by AccountId]){
           
           acc.id = String.valueof(ar.get('accId'));
           acc.Over_all_Rating__c = Integer.valueOf(ar.get('ratid'));
           acc.Number_of_Contact__c = Integer.valueOf(ar.get('countid'));
           overallrating.add(acc);
          
           
           
           
           System.debug('<<>>'+overallrating);
            
        }
      
    update overallrating;
    
}


 
Pradeep SinghPradeep Singh
Hi,
For triggers, you just have to do the DMLs as same as your events.
1. Create Account test data Record/s.
2. Create Contact test data Records with all the fields value for which you are aggregating.
3. Updae contact records by changing the field values.
4. Delete and Undelete the contact records.

This will automatically call the trigger on applying DML on test data.